export class LogWebSocket {
  websocketUrl = "";
  websocket = null;
  lockReconnect = true;

  // eslint-disable-next-line class-methods-use-this
  initCallback = (e) => {};
  // eslint-disable-next-line class-methods-use-this
  websocketCallBack = (e) => {};

  initWebSocket() {
    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
    // eslint-disable-next-line
    this.lockReconnect = false;
    this.websocket = new WebSocket(this.websocketUrl);
    this.websocket.onopen = (e) => {
      if (typeof this.initCallback === "function") {
        this.initCallback(e);
      }
    };
    this.websocket.onerror = () => {
      this.reconnect();
    };
    this.websocket.onmessage = (e) => {
      if (typeof this.websocketCallBack === "function") {
        this.websocketCallBack(e.data);
      }
    };
    this.websocket.onclose = (e) => {
      this.reconnect();
    };
  }

  closeWebsocket() {
    this.lockReconnect = true;
    this.websocket.close();
  }

  websocketSend(text) {
    // 数据发送
    try {
      this.websocket.send(text);
    } catch (err) {}
  }

  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    setTimeout(() => {
      this.initWebSocket();
      this.lockReconnect = false;
    }, 1000);
  }
}

export default {};
