import { Injectable, Inject } from '@angular/core';
import * as signalR from "@aspnet/signalr";
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { HttpHeaders, HttpParams, HttpClient } from '@angular/common/http';
import { Data } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';
import { ConnectionIndicationService } from './ConnectionIndication.service';
import { AuthService } from '../auth/auth.service';
import { AppConfig } from '../AppConfig/AppConfig';
import { LocalContainerObject } from '../interface/Interactive Component/LocalContainerObject';

@Injectable({
  providedIn: 'root'
})
export class WebNotificationService {
    connection:signalR.HubConnection;
    connectionisvalid:boolean=true;
    connectionbroken:boolean=false;
    func: Function;
    typestr:string;
    syncserviceUrl:string;
    milisecond:number;
    @BlockUI() blockUI: NgBlockUI;
    intervalfunc:any;
    constructor(private authService: AuthService,
      public http: HttpClient,
      @Inject('syncserviceurl') syncserviceUrl: string)
    {
      this.syncserviceUrl=syncserviceUrl;
    
     
    }
    




  build()
  {
  // alert('sss');
    this.connection = new signalR.HubConnectionBuilder()
        .withUrl(AppConfig.settings.syncserviceurl+"NotificationHub",
      {  accessTokenFactory: () => 
      
       this.authService.getAccessToken()
    })
        .build();
        
            ConnectionIndicationService.ConnectionStatusChanged.subscribe(online=>
              {
        if(online)
        {
          this.start();
          // alert('start');
        }else
        {
        this.stop();
        // alert('stop');
        }
        // alert('sss2');
              });
        
        //  this.connection = new signalR.HubConnectionBuilder()
        // .withUrl(AppConfig.settings.syncserviceurl+"NotificationHub", signalR.HttpTransportType.WebSockets)
        // .build();
        this.connection.serverTimeoutInMilliseconds=3600000;
        // this.ConnectionStatusChanged.next(false);
        // this.connection.onclose((e)=>{
        //   // this.blockUI.start('Reconnecting...');
        //   // this.intervalfunc =setInterval(() => {
        //   //   // this.ConnectionCheck(); 
        //   // }, 5000);
        //   // this.connectionisvalid=false;
        //   this.stop();
        // });

        return this.connection;
  }

on(func: Function,typestr:string)
{
  this.func=func;
  this.typestr=typestr;
    this.connection.on("ClientMessage", data => {
        let f = data as LocalContainerObject;
        // alert(JSON.stringify(f));
        // var blob = new Blob([JSON.stringify(f)], { type: 'text/csv' });
        // saveAs(blob,"ssss.txt");
      //   this.messageService.add({severity:'Info', summary:'Info', detail:f.guid});
      // alert(f.type);
      if (f.type==typestr)
      {func(data);}
       
         
        });

       
}

start()
{
  // alert('sss3');
    this.connection.start().then(() => {
      console.log('Hub Web Notification connection started');
  }).catch(err=>{
        // alert('Error while establishing connection');
  });


}

off()
{
  this.connection.off("ClientMessage");

}
  stop()
  {

    this.connection.stop().then(()=>{

    
    }).catch(function (err) {
      alert('Error while establishing connection');
  });
   
  }
}
