import {Injectable} from "@angular/core";

@Injectable({providedIn: 'root'})
export class WebsocketService {

  private initialData;

  public subscribe(fn: Function): void {
    let property = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data");
    const data = property.get;
    this.initialData = data;

    // wrapper that replaces getter
    function lookAtMessage() {
      let socket = this.currentTarget instanceof WebSocket;

      if (!socket || !this.currentTarget.url.endsWith('notifier.message.send.push')) {
        return data.call(this);
      }
      let msg = data.call(this);
      Object.defineProperty(this, "data", { value: msg }); //anti-loop
      fn({ data: msg, socket: this.currentTarget, event: this });
      return msg;
    }
    property.get = lookAtMessage;
    Object.defineProperty(MessageEvent.prototype, "data", property);
  }

  public unsubscribe(): void {
    let property = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data");

    if (this.initialData) {
      property.get = this.initialData;
      Object.defineProperty(MessageEvent.prototype, "data", property);
    }
  }
}
