import { WebsocketMessageReceive } from './WebSocketMessage.js'

function connect(editor) {
  const host = 'ws://' + editor.ip + '//WebModule//websocket'
  let timeout = null
  const websocketMessageReceive = new WebsocketMessageReceive(editor)
  // 尝试连接至服务器
  try {
    if ('WebSocket' in window) {
      editor.socket = new WebSocket(host)
    } else {
      editor.showMessage('浏览器不支持WebSocket', 'error', 2000)
    }
  } catch (exception) {
    editor.showMessage('与服务器断开连接', 'error', 2000)
    return
  }
  // 连接成功
  editor.socket.onopen = function() {
    // 关闭timer
    try {
      clearInterval(timeout)
    } catch (exception) {
      console.log(exception)
    }
    const name = editor.opname
    editor.socket.send('LIN,' + name)
    editor.showMessage('加载完成，连接服务器成功！', 'success', 2000)
    editor.isOk = true
    websocketMessageReceive.getOriginTagValue()
    // let a = 0
    // setInterval(() => {
    //   a += 0.5
    //   const message = `DT|JointMoveTo|0f26fc6e-1caf-4f57-beb3-d8a65872fbdd|{"J1":"${a}","J2":"0","J3":"0","J4":"0","J5":"0","J6":"0","J7":"0","J8":"0","J9":"0","J10":"0","J11":"0","J12":"0"}`
    //   websocketMessageReceive.websocketMessage({ data: message })
    // }, 10)
  }
  // 收到消息
  editor.socket.onmessage = function(msg) {
    try {
      websocketMessageReceive.websocketMessage(msg)
    } catch (exception) {
      const error = exception.toString()
      console.log(error)
    }
  }
  // 连接断开
  editor.socket.onclose = function(event) {
    try {
      editor.showMessage('onclose' + '服务器连接失败', 'error', 2000)
      editor.socket.close()
      if (editor.IsAllowConnect) {
        // 显示一下
        editor.showMessage('重新连接服务器', 'warning', 2000)
        console.log('onclose' + '重新连接服务器')
        // 重新连接,打开计时器
        timeout = setTimeout(function() {
          connect(editor)
        }, 5000)
      }
    } catch (exception) {
      const error = exception.toString()
      editor.showMessage.error('服务器出现错误,关闭连接' + error, 'error', 2000)
    }
  }
  // 出现错误
  editor.socket.onerror = function(event) {
    console.log('onerror_' + '服务器连接失败')
    editor.showMessage.error('服务器连接失败', 'error', 2000)
  }
}

export { connect }

