import { Component, OnInit } from '@angular/core';
import { EmployeesListItem, EmployeesListResponse } from '../../../../interfaces/personal-managment/employee.interface';
import { SubcontratistItem, SubcontratistsResponse } from '../../../../interfaces/personal-managment/subcontratists.interface';
import { FormControl, Validators } from '@angular/forms';
import { EmployeeService } from '../../../../services/personal-management/employee.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { EncService } from '../../../../services/enc.service';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-block-dialog',
    templateUrl: './block-dialog.component.html',
    styleUrl: './block-dialog.component.css',
    standalone: false
})
export class BlockDialogComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  employees: EmployeesListItem[];
  subcontratists: SubcontratistItem[];
  formControl: FormControl;

  constructor(
    private _employeeService: EmployeeService,
    private _subcontratistService: SubcontratistService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<BlockDialogComponent>,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.employees = [];
    this.subcontratists = [];
    this.formControl = new FormControl('', Validators.required);
  }

  ngOnInit(): void {
    this.getEmployees();
  }

  async getEmployees(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let employees: EmployeesListResponse = await lastValueFrom(this._employeeService.getConsultOfEmployees(idUser, 1));

      this.hasError = employees.error;
      this.errorStr = employees.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let employeesArr: EmployeesListItem[] = [];
        for(const employee of employees.response){
          let idDec = await this._encService.decrypt(employee.ID_EMPLOYEE);
          employee.NAME = `${employee.NAME} (${idDec})`;
          if(employee.STATUS == 'Activo'){
            employeesArr.push(employee);
          }
        }

        this.employees = employeesArr;
        this.getSubcontratists();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getSubcontratists(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let subcontratists: SubcontratistsResponse = await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(idUser, 1));
      
      this.hasError = subcontratists.error;
      this.errorStr = subcontratists.msg;

      if(!this.hasError){
        let subcontratistsArr: SubcontratistItem[] = [];
        for(const subcontratist of subcontratists.response){
          let idDec = await this._encService.decrypt(subcontratist.ID_SUBCONTRATIST);
          subcontratist.NAME = `${subcontratist.NAME} (${idDec})`;
          if(subcontratist.STATUS == 'Activo'){
            subcontratistsArr.push(subcontratist);
          }
        }

        this.subcontratists = subcontratistsArr;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async confirmBlock(){
    let blockedArr = this.formControl.value.split('|');
    let blockedStr = await this._encService.decrypt(blockedArr[0]);
    let blockedType = blockedArr[1] == 'USR' ? 'empleado' : 'subcontratista';
    let blockedName = '';

    if(blockedType == 'empleado'){
      for(const employee of this.employees){
        let idDec = await this._encService.decrypt(employee.ID_EMPLOYEE as string);
        if(idDec == blockedStr){
          blockedName = employee.NAME;
        }
      }
    }else{
      for(const subcontratist of this.subcontratists){
        let idDec = await this._encService.decrypt(subcontratist.ID_SUBCONTRATIST as string);
        if(idDec == blockedStr){
          blockedName = subcontratist.NAME;
        }
      }
    }
    
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      maxWidth: '420px',
      disableClose: true,
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: `¿Está seguro de querer bloquear al ${blockedType} ${blockedName}?`,
        description2: `Esta acción evitará que el ${blockedType} esté disponible para realizar órdenes de trabajo.`
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this._dialogRef.close(this.formControl.value);
      }
    });
  }
}
