export interface PogWebsocketListener {
  OnMessage(data: any): void;
}

export class PogWebsocket {
  public static create(url: string, message: PogWebsocketListener) {
    let pogWebsocket = new PogWebsocket();
    pogWebsocket.init(url, message);
    return pogWebsocket;
  }

  public get connected(): boolean {
    return this._connected;
  }

  ping() {
    if (!this._connected) {
      return;
    }
    let pingData = "ping";
    this._ws.send(pingData);
  }

  //   private _url: string;
  private _ws: WebSocket;

  private _connected: boolean = false;

  private _message: PogWebsocketListener;

  private init(url: string, message: PogWebsocketListener) {
    // this._url = url;
      this._message = message;

    this._ws = new WebSocket(url);
    let self = this;
    this._ws.onopen = this.onOpen.bind(this);
    this._ws.onmessage = this.onMessage.bind(this);
    this._ws.onclose = this.onClose.bind(this);
    this._ws.onerror = this.onError.bind(this);
  }

  private onOpen() {
    console.log("onOpen");
    this._connected = true;
    // this._ws.send(
    //   JSON.stringify({
    //     type: "test",
    //     data: "test",
    //   })
    // );
  }

  private onMessage(data: MessageEvent) {
    if (data.data == "pong") {
      return;
    }
    this._message.OnMessage(data);
  }

  private onClose(event: CloseEvent) {
    console.log("onClose", event);
    this._connected = false;
  }

  private onError(event: Event) {
    console.log("onError", event);
    this._connected = false;
  }

  public async send(data: any) {
    if (!this._connected) {
      return;
    }
    await this._ws.send(data);
  }

  public close() {
    this._ws.close();
  }
}
