import { NgClass } from '@angular/common';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { AfterViewInit, Component, OnInit, inject } from '@angular/core';
import { FormGroup, FormBuilder, ReactiveFormsModule, FormsModule } from '@angular/forms';
import { DropDownFilterSettings, KENDO_DROPDOWNS } from '@progress/kendo-angular-dropdowns';

import { AlertService } from '../components/alert';
import { IdleMonitorService } from '../idleMonitor.service';
import { FunctionService } from '../components/models/function.service';
import { AuthenticationService } from '../../providers/user/authentication.service';
import { ConfigurationService } from '../app.config.service';


@Component({
  standalone: true,
  selector: 'logout-child',
  templateUrl: './logoutChild.component.html',
  imports: [FormsModule, ReactiveFormsModule, NgClass, KENDO_DROPDOWNS]
})
export class LogoutChildComponent implements OnInit, AfterViewInit
{
  private readonly fnSvc = inject(FunctionService);
  private readonly formBuilder = inject(FormBuilder);
  private readonly alertService = inject(AlertService);
  private readonly activeModal = inject(NgbActiveModal);
  private readonly idleSvc = inject(IdleMonitorService);
  private readonly configSvc = inject(ConfigurationService);
  private readonly authService = inject(AuthenticationService);

  public logoutForm: FormGroup;
  public submitted: boolean = false;
  public logoutTimeOnly: string = '';
  public earlyLogoutRemarks: any[] = [];
  public remarksRequired: boolean = false;
  public attendanceEnabled: boolean = false;
  public filterSettings: DropDownFilterSettings = { caseSensitive: false, operator: "contains" };

  private hostName: string = '';
  private ipAddress: string = '';
  private macAddress: string = '';

  ngOnInit()
  {
    this.logoutForm = this.formBuilder.group(
      {
        atndnceLogout: false,
        logoutRemarks: ''
      });

    this.authService.getLogoutRemarks().subscribe(
      {
        next: (resp: any) =>
        {
          if (resp.returnStatus === 200)
          {
            this.earlyLogoutRemarks = resp.value ?? [];
          }
          else
          {
            this.earlyLogoutRemarks = [];
          }
        },
        error: () =>
        {
          this.earlyLogoutRemarks = [];
        }
      });
  }

  ngAfterViewInit(): void
  {
    const compConfig = this.configSvc.configuration?.computerConfig;
    if (compConfig)
    {
      if (compConfig.status === 998)
      {
        this.attendanceEnabled = false;
        this.alertService.error(`It's seems, You are using AnyDesk (${compConfig.remoteHost}).`);
      }
      else if (compConfig.status === 999)
      {
        this.attendanceEnabled = false;
        this.alertService.error(`It's seems, You are using Remote Desktop (${compConfig.remoteHost}).`);
      }
      else
      {
        this.hostName = this.fnSvc.cipherData(compConfig.hostName);
        this.ipAddress = this.fnSvc.cipherData(compConfig.ipAddress);
        this.macAddress = this.fnSvc.cipherData(compConfig.macAddress);
        this.attendanceEnabled = this.authService.currentUserValue.logoutTime && compConfig.ipAddress?.length > 0;

        const currentTime: Date = new Date();
        const lgogoutTime = new Date(this.authService.currentUserValue.logoutTime);
        this.remarksRequired = this.authService.currentUserValue.logoutTime && currentTime < lgogoutTime;
        this.logoutTimeOnly = this.authService.currentUserValue.logoutTime ? ` (${this.fnSvc.toFormattedDate(lgogoutTime, 'H:mm')})` : '';
      }
    }
  }

  public eventCheck(event: any): void
  {
    if (event?.target?.checked && this.remarksRequired)
    {
      this.fnSvc.setValidatorsToToControl({ control: this.f.logoutRemarks, required: 1, regExp: '' });
    }
    else
    {
      this.f.logoutRemarks.clearValidators();
      this.f.logoutRemarks.updateValueAndValidity();
    }
  }

  get f() { return this.logoutForm.controls; }

  public okay(): void
  {
    this.submitted = true;
    if (this.logoutForm.invalid)
      return;

    if (this.f.atndnceLogout.value)
    {
      const logoutRemarks: string = this.f.logoutRemarks.value ?? '';
      this.authService.logout(true, this.ipAddress, this.macAddress, this.hostName, logoutRemarks)?.subscribe(
        {
          next: () =>
          {
            this.idleSvc.stopMonitor();
            this.authService.loggedout();
            this.activeModal.close(true);
          },
          error: (error: any) =>
          {
            this.alertService.clear();
            this.alertService.error(error);
          }
        });
    }
    else
    {
      this.authService.logout()?.subscribe(
        {
          next: () =>
          {
            this.idleSvc.stopMonitor();
            this.authService.loggedout();
            this.activeModal.close(true);
          },
          error: () =>
          {
            this.authService.loggedout();
          }
        });
    }
  }

  public close(): void
  {
    this.activeModal.close(false);
  }
}
