import i18n from '@/locales'

const { t } = i18n.global

export default class WebSocketCtr {
  private socket: WebSocket | null = null
  private readonly url: string

  public isDisconnect: boolean = true

  constructor(url: string) {
    this.url = url
  }

  private initSocket(callBack?: () => void) {
    const socket = new WebSocket(this.url)

    socket.onopen = () => {
      this.isDisconnect = false

      this.onConnect()

      callBack && callBack()
    }

    socket.onmessage = (event: any) => {
      let data: any = { final: false }

      try {
        data = JSON.parse(event.data)
      } catch (err) {
        window.$message.error(t('common_module.response_error'))

        this.onMessageError()
      }

      if (data.code && data.code !== '0') {
        if (this.socket) {
          this.socket.close()
          this.socket = null
        }

        this.onMessageError()

        return
      }

      this.onMessage(data)
    }

    socket.onerror = (event) => {
      this.onError(event)
    }

    socket.onclose = () => {
      this.isDisconnect = true

      this.onDisconnect()
    }

    this.socket = socket
  }

  connect(callBack?: () => void) {
    if (this.socket && [0, 1].includes(this.socket.readyState)) {
      callBack && callBack()
      return
    }

    this.initSocket(callBack)
  }

  send(content: { [k: string]: any }) {
    this.socket && this.socket.send(JSON.stringify(content))
  }

  disconnect() {
    if (this.socket) {
      this.socket.close()
      this.socket = null
    }

    this.onDisconnect()
  }

  /* call back */
  onConnect() {}
  onMessage(_message: any) {}
  onMessageError() {}
  onError(_event?: any) {}
  onDisconnect() {}
}
