import { Injectable } from '@angular/core';
import {Observable, Subscriber} from 'rxjs';



@Injectable()
export class WebSocketService {

  public ws: WebSocket;
  private url: string;
  private observer: Subscriber<string>;

  public createObservableSocket(url: string): Observable<string> {
    this.url = url;
    const ret = new Observable<string> ( observer => {
      this.observer = observer;
    });
    this.startWebsocket();
    return ret;
  }

  // tslint:disable-next-line:typedef
  public onMessage(event){
    this.observer.next(event.data);
  }

  // tslint:disable-next-line:typedef
  public onError(event){
    console.log('on error ', event);
  }

  // tslint:disable-next-line:typedef
  public onClose(event){
    console.log('websocket closed.. reconnect in 1s ..');
    setTimeout(() => { this.startWebsocket(); } , 1000);
  }

  // tslint:disable-next-line:typedef
  public startWebsocket() {
    console.log('starting websocket now..', this.url);
    this.ws = new WebSocket(this.url);
    this.ws.onmessage = this.onMessage.bind(this);
    this.ws.onerror = this.onError.bind(this);
    this.ws.onclose = this.onClose.bind(this);
  }

  public sendMessage(message: any): void {
    this.ws.send(message);
  }
}
