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

function connectMqtt(editor) {
  const connection = {
    host: editor.mqttHost,
    port: editor.mqttPort,
    endpoint: '/mqtt',
    clean: true, // 保留会话
    connectTimeout: 4000, // 超时时间
    reconnectPeriod: 4000, // 重连时间间隔
    // 认证信息
    clientId: 'mqttjs_3be2c321' + new Date().getTime(), // 同一个ID 无法二次连接
    username: '',
    password: ''
  }
  const subscription = {
    topic: editor.opname,
    qos: 0
  }
  const websocketMessageReceive = new WebsocketMessageReceive(editor)

  const { host, port, endpoint, ...options } = connection
  const wsHeaderString = location.protocol === 'https:' ? 'wss' : 'ws'
  // const connectUrl = `${wsHeaderString}://${location.host}${endpoint}`
  const connectUrl = `${wsHeaderString}://${host}:${port}${endpoint}`
  console.log(connectUrl)
  try {
    editor.mqttClient = mqtt.connect(connectUrl, options)
  } catch (error) {
    console.log('MQTT connect error', error)
  }
  editor.mqttClient.on('connect', () => {
    editor.showMessage('加载完成，连接MQTT服务器成功！', 'success', 2000)
    console.log('MQTT Connection succeeded!')
    editor.isOk = true
    const { topic, qos } = subscription
    editor.mqttClient.subscribe(topic, { qos }, (error, res) => {
      if (error) {
        console.log('Subscribe to topics error', error)
        return
      }
      websocketMessageReceive.getOriginTagValue()
    })
  })
  editor.mqttClient.on('error', error => {
    console.log('MQTT Connection failed', error)
    try {
      editor.showMessage('MQTT服务器连接失败', 'error', 2000)
      editor.socket.close()
      if (editor.IsAllowConnect) {
        // 显示一下
        editor.showMessage('重新连接MQTT服务器', 'warning', 2000)
        console.log('重新连接MQTT服务器')
        // 重新连接,打开计时器
        setTimeout(function() {
          connectMqtt(editor)
        }, 5000)
      }
    } catch (exception) {
      const error = exception.toString()
      editor.showMessage.error('MQTT服务器出现错误,关闭连接' + error, 'error', 2000)
    }
  })
  // 接收消息
  editor.mqttClient.on('message', (topic, message) => {
    try {
      websocketMessageReceive.websocketMessage({ data: message.toString() })
    } catch (exception) {
      console.log(exception.toString())
    }
  })
  editor.mqttClient.on('close', () => {
    editor.mqttClient.end()
  })
}
export { connectMqtt }

