// const WsConnecting = 0
const WsOpen = 1
// const WsClosing = 2
// const WsClosed = 3

export default class XWebSocket {
  addr = ''
  client = null
  autoConnect = false
  interval = undefined
  delay = 60
  on = { open: null, message: null, error: null, close: null }

  // constructor
  constructor ({ open, message, error, close, delay, autoConnect }) {
    this.on = { open, message, error, close }

    if (delay >= 0) {
      this.delay = delay
    }

    this.autoConnect = autoConnect
  }

  // 连接
  connect (addr) {
    this.addr = addr
    this._wsInit()
  }

  // 发送
  send (data) {
    if (this.client && this.client.readyState === WsOpen) {
      this.client.send(data)
    }
  }

  // 关闭
  close () {
    if (!this.client) return

    this._breforeClose(false)

    this.client.close()
    this.client = null
  }

  _breforeClose (autoConnect) {
    this._wsClearHeartbeat()

    if (this.client) {
      if (!autoConnect) {
        // 防止 onclose 中实现 断线重连
        this.client.onclose = undefined
      }
    }
  }

  _wsInit () {
    const _self = this

    this.client = new window.WebSocket(this.addr)
    this.client.onopen = this.on.open
    this.client.onmessage = this.on.message
    this.client.onerror = this.on.error
    this.client.onclose = e => {
      if (_self.on.close) {
        _self.on.close(e)
      }

      _self._breforeClose(_self.autoConnect)
      _self.client = null

      if (_self.autoConnect) {
        window.setTimeout(() => _self._wsInit(), _self.delay * 1000)
      }
    }

    this._wsHeartbeat()
  }

  _wsHeartbeat () {
    this.interval = window.setInterval(() => {
      if (this.client && this.client.readyState === WsOpen) {
        this.client.send(10)
      }
    }, 60 * 1000)
  }

  _wsClearHeartbeat () {
    if (this.interval !== undefined) {
      window.clearInterval(this.interval)
    }
  }
}
