import mqtt from 'mqtt/dist/mqtt'

let client
let mqttUrl = process.env.VUE_APP_MQTT_URL
let topic = process.env.VUE_APP_FQLDP_TOPIC
let qos = process.env.VUE_APP_FQLDP_TOPIC_QOS
export function open (callback) {
  if (client !== undefined && client.connected) {
    return ''
  }
  let options = {
    keepalive: 60,
    reschedulePings: true,
    protocolId: 'MQTT',
    protocolVersion: 4,
    reconnectPeriod: 1000,
    connectTimeout: 30 * 1000,
    // clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: '',
    password: '',
    clientId: 'FQLDP_Client_' + Math.random().toString(16).substr(2, 8),
    clean: true,
    resubscribe: true
  }
  client = mqtt.connect(mqttUrl, options)
  client.on('connect', (connack) => {
    console.log('连接成功')
    client.subscribe(topic, {qos: parseInt(qos)}, (err, granted) => {
      console.debug('订阅响应', err, granted)
    })
  })
  client.on('reconnect', () => {
    console.log('重接连接')
  })
  client.on('close', () => {
    console.log('关闭连接')
  })
  client.on('disconnect', (packet) => {
    console.log('MQTT5代理断开连接包:' + packet)
  })
  client.on('error', (error) => {
    console.error('TLS错误:' + error)
  })
  client.on('offline', () => {
    console.error('客户端离线')
  })
  client.on('packetsend', (packet) => {
    console.debug('发送数据', packet)
  })
  client.on('packetreceive', (packet) => {
    console.debug('接收数据', packet)
    switch (packet.cmd) {
      case 'suback':
        if (packet.granted.length > 0 && packet.granted[0] === 128) {
          console.error('订阅失败', packet.granted)
          close()
        } else {
          console.log('订阅成功')
        }
        break
    }
  })
  client.on('message', (topic, message, packet) => {
    // message is Buffer
    console.debug(topic, message.toString())
    callback(message)
  })
}

export function close () {
  if (client !== undefined && !client.disconnecting) {
    client.end()
  }
}

export default {
  open,
  close
}
