import {Injectable} from '@angular/core';
import {NGXLogger} from 'ngx-logger';
import {fromEvent, interval, Observable} from 'rxjs';

import {environment} from '../../environments/environment';
import {WSEvents} from '../interfaces/interface';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  private wsEndpoint = environment.ws_location + ':' + environment.ws_port + '/test-ws-endpoint/';
  private readonly ws: WebSocket;
  private wsEvents: WSEvents;

  constructor(private logger: NGXLogger) {
    this.logger.debug('Initiating ws connection on', this.wsEndpoint);
    this.ws = new WebSocket(this.wsEndpoint);

    interval(5000).subscribe(() => {
      // continuously check if the connection is still open
      if (this.ws.readyState !== WebSocket.OPEN) {
        this.logger.error('Lost websocket connection ...', this.ws);
      }
    });

  }

  wsTestCall(msg: string): WSEvents {
    this.logger.debug(
      'Performing ws test call',
      'current ws ready state ==', this.ws.readyState + ',',
      'expected == 1 == open');

    if (this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(msg);
    } else {
      return undefined;
    }

    if (!this.wsEvents) {
      this.wsEvents = {
        message: fromEvent(this.ws, 'message'),
        error: fromEvent(this.ws, 'error'),
        close: fromEvent(this.ws, 'close')
      };
    }

    return this.wsEvents;
  }

}
