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: 'dmtmqttjs_3be2c321' + new Date().getTime(), // 同一个ID 无法二次连接
    username: '',
    password: '',
  }
  const subscription = {
    topic: editor.opname,
    qos: 0,
  }
  const websocketMessageReceive = new WebsocketMessageReceive(editor)
  window.websocketMessageReceive = websocketMessageReceive

  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()
    })
    if (editor.currentMode === 'SM') {
      const msg = `DT|PlayAct|${editor.autoPlayCraftCode}|1`
      websocketMessageReceive.websocketMessage({ data: msg.toString() })
    }
  })
  editor.mqttClient.on('error', (error) => {
    console.log('MQTT Connection failed', error)
    editor.showMessage('MQTT服务器出现错误,关闭连接' + error, 'error', 2000)
  })
  // 接收消息
  editor.mqttClient.on('message', (topic, message) => {
    try {
      if (editor.currentMode === 'DT') {
        websocketMessageReceive.websocketMessage({ data: message.toString() })
      }
    } catch (exception) {
      console.log(exception.toString())
    }
  })
  editor.mqttClient.on('close', () => {
    console.log('MQTT Connection close')
    editor.showMessage('MQTT服务器关闭连接', 'error', 2000)
  })
  editor.mqttClient.on('offline', () => {
    console.log('MQTT Connection offline')
    editor.showMessage('MQTT服务器离线', 'error', 2000)
  })
}
export { connectMqtt }
