const Store = require('electron-store')
const localStore = new Store()

export default class HuashiReaderWsApi {
  constructor () {
    this.statusArr = [
      { state: 0, value: '正在连接' },
      { state: 1, value: '已建立连接' },
      { state: 2, value: '正在关闭连接' },
      { state: 3, value: '已关闭连接' }
    ]
    this.websockets = null
    this.isConnected = false
    this.messageListeners = [] // Listeners for incoming messages
    this.connectCallback = null
  }

  // 建立连接
  connect (cb) {
    this.connectCallback = cb
    let url = localStore.get('idDeviceUrl') || ''

    if (!url.startsWith('ws://')) {
      url = url.replace('http://', 'ws://').replace('https://', 'ws://')

      if (!url) {
        url = 'ws:127.0.0.1:8800'
      }
    }
    if (!this.isConnected) {
      this.websockets = new WebSocket(url)

      this.websockets.onopen = () => this.socketChange()
      this.websockets.onmessage = (res) => this.handleMessage(res)
      this.websockets.onclose = () => this.socketChange()
    } else {
      this.closeConnect()
    }
  }

  // 处理接收到的消息
  handleMessage (res) {
    // Notify all listeners about the new message
    this.messageListeners.forEach(listener => listener(res))

    if (res.data === 'failed to obtain ID card information') {
      return false
    }
  }

  // 添加消息监听器
  addMessageListener (listener) {
    if (typeof listener === 'function') {
      this.messageListeners.push(listener)
    }
  }

  // 移除消息监听器
  removeMessageListener (listener) {
    this.messageListeners = this.messageListeners.filter(l => l !== listener)
  }

  // 发送消息
  sendMessage (message) {
    if (this.isConnected && this.websockets) {
      this.websockets.send(message)
    }
  }

  // 读取身份证（带超时）
  timeOutReadIDCard (timeout) {
    this.sendCommand('02', `timeout=${timeout}`)
  }

  // 读取身份证
  readIDCard (timeout) {
    this.sendCommand('03', `timeout=${timeout}`)
  }

  // 读取身份证（无判断）
  readIDCardNoJudge (timeout) {
    this.sendCommand('04', `timeout=${timeout}`)
  }

  // 读取 SAM ID
  readSAMID (timeout) {
    this.sendCommand('05', `timeout=${timeout}`)
  }

  // 发送命令
  sendCommand (command, parameters) {
    const val = `${command}?${parameters}`
    this.sendMessage(val)
  }

  // 处理 socket 状态变化
  socketChange () {
    const state = this.websockets.readyState

    if (state === 1) {
      this.isConnected = true
    } else if (state === 3) {
      this.isConnected = false
    }

    if (this.connectCallback && typeof this.connectCallback === 'function') {
      this.connectCallback(this.isConnected)
    }
  }

  // 获取连接状态
  getConnectionStatus () {
    return this.isConnected
  }

  // 关闭连接
  closeConnect () {
    if (this.websockets) {
      this.websockets.close()
    }
    this.clear()
  }

  // 清理数据
  clear () {
    this.messageListeners = []
  }
}
