import { Injectable, inject } from '@angular/core'
import { NotificationService } from "@progress/kendo-angular-notification"
import { HubConnection, HubConnectionBuilder, LogLevel } from '@microsoft/signalr';

import { environment } from "../environments/environment"
import { AuthenticationService } from "../providers/user/authentication.service"

@Injectable({ providedIn: 'root' })
export class SignalRService
{
  private readonly notifySvc = inject(NotificationService);
  private readonly authSvc = inject(AuthenticationService);

  private authHub: HubConnection;
  private notifHub: HubConnection;

  public monitorAuthenticationHub(): void
  {
    this.authHub = new HubConnectionBuilder()
      .withUrl(`${environment.apiUrl}authenticationHub`)
      .configureLogging(LogLevel.Warning)
      .withAutomaticReconnect()
      .build();

    this.authHub.start()
      .then(() => { })
      .catch(() => { });

    this.authHub.on('NotifySubscriber', (userId: number, msgType: number, ipAddress: string) =>
    {

      if (!this.authSvc.currentUserValue?.id || !userId || userId !== this.authSvc.currentUserValue?.id)
        return;

      if (msgType === 1)  //Force logout
      {
        if (!this.authSvc.currentUserValue?.logId)
          return;

        this.authSvc.logout()?.subscribe(
          {
            next: () => { this.authSvc.loggedout() },
            error: () => { this.authSvc.loggedout() }
          });
      }
      else if (msgType === 2)  //Same user longin from different device/browser
      {
        this.notifySvc.show({
          content: `You are Logged in from another device (Ip address: ${ipAddress})`,
          hideAfter: 3000,
          position: { horizontal: "center", vertical: "top" },
          animation: { type: "slide", duration: 500 },
          type: { style: "error", icon: true },
          cssClass: 'k-notification-top'
        });
      }
    });
  }

  public monitorNotificationHub(): void
  {
    this.notifHub = new HubConnectionBuilder()
      .withUrl(`${environment.apiUrl}signalRHub`)
      .configureLogging(LogLevel.Warning)
      .withAutomaticReconnect()
      .build();

    this.notifHub.start()
      .then(() => { })
      .catch(() => { });

    this.notifHub.on('NotifySubscriber', (userId: number, msgType: number, itemId: number, ipAddress: string) =>
    {
      if (msgType === 6)
      {
        if (!this.authSvc.currentUserValue?.logId)
          return;

        //Raise pending authorization pening event
        this.authSvc.raiseAtnLoginEvent(true);
      }
      else if (msgType === 5)
      {
        if (!this.authSvc.currentUserValue?.logId)
          return;

        //Raise pending authorization pening event
        this.authSvc.raiseNotificationEvent(true);
      }
      else if (msgType === 3 || msgType === 4)
      {
        if (!this.authSvc.currentUserValue?.logId || this.authSvc.currentUserValue.id === userId)
          return;

        //Sub task Status changed/Remarks added (Same user/Other team space will not be notified) 
        this.authSvc.raiseTaskStatusEvent(userId, msgType, itemId);
      }
      else
      {
        if (!this.authSvc.currentUserValue?.id || !userId || userId !== this.authSvc.currentUserValue?.id)
          return;

        if (msgType === 1)  //Force logout
        {
          if (!this.authSvc.currentUserValue?.logId)
            return;

          this.authSvc.logout()?.subscribe(
            {
              next: () => { this.authSvc.loggedout() },
              error: () => { this.authSvc.loggedout() }
            });
        }
        else if (msgType === 2)  //Same user longin from different device/browser
        {
          this.notifySvc.show({
            content: `You are Logged in from another device (Ip address: ${ipAddress})`,
            hideAfter: 3000,
            position: { horizontal: "center", vertical: "top" },
            animation: { type: "slide", duration: 500 },
            type: { style: "error", icon: true },
            cssClass: 'k-notification-top'
          });
        }
      }
    });
  }

  public stopAuthenticationHub(): void
  {
    if (this.authHub)
    {
      this.authHub.stop().then(() => { }).catch(() => { });
    }
  }

  public stopNotificationHub(): void
  {
    if (this.notifHub)
    {
      this.notifHub.stop().then(() => { }).catch(() => { });
    }
  }
}
