import { EventEmitter, Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder, IStreamResult } from '@aspnet/signalr'
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { environment } from '../../environments/environment';
import * as signalR from '@aspnet/signalr';

@Injectable()
export class loginSignalRService {
  connectionEstablished = new EventEmitter<Boolean>();
  marketOpened = new EventEmitter<Boolean>();
  marketClosed = new EventEmitter<Boolean>();
  baseurl: string
  private connectionIsEstablished = false;
  private _loginHubConnection: HubConnection;


  constructor(private authService: AuthService, private router: Router
  ) {
  }

  createConnection() {
    this.baseurl = environment.serviceUrl;
    this._loginHubConnection = new HubConnectionBuilder()
      .withUrl(this.baseurl + 'authhub?userid=' + localStorage.getItem("userid"), {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .build();
  }


  startConnection(): void {

    this._loginHubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        //console.log('Lnotes connection started');
        this.connectionEstablished.emit(true);
      }).catch(err => {
        //console.log('Error while establishing connection');
      });


  }


  stopconnection(): void {

    this._loginHubConnection
      .start();
    this._loginHubConnection
      .stop();


  }
  registerOnServerEvents(): void {
    this._loginHubConnection.on("Logoutclient", (clientid: string) => {
      //console.log("Logoutclient");

      //console.log(clientid);
      var userid = localStorage.getItem("userid");
      if (clientid == userid) {
        this._loginHubConnection.stop();
        //this.authService.logout();
        localStorage.clear();
        localStorage.removeItem("LoggedIn");
        this.router.navigate(['login']);
      }

    });


  }



}  
