import { Component, OnInit, ViewChild } from '@angular/core';
import { OccupationAreasListItem, OccupationAreasListResponse, OccupationsListItem, OccupationsListResponse } from '../../../interfaces/equipment-management.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { EncService } from '../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { FunctionsService } from '../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { NewOccupationComponent } from './new-occupation/new-occupation.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-occupation-management',
    templateUrl: './occupation-management.component.html',
    styleUrl: './occupation-management.component.css',
    standalone: false
})
export class OccupationManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  occupationAreas: OccupationAreasListItem[];

  dataSource: MatTableDataSource<OccupationsListItem>;
  displayedColumns = ['AREA', 'OCUPACION', 'DESC', 'ESTADO', 'ULMOD', 'ACCIONES'];

  public txtBuscador:string;

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    private _equipmentManagementService: EquipmentManagementService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.occupationAreas = [];
    this.txtBuscador = '';

    this.dataSource = new MatTableDataSource();
  }

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

  async getData(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let occupationAreas: OccupationAreasListResponse = await lastValueFrom(this._equipmentManagementService.occupationAreasConsult(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        for(const occupationArea of occupationAreas.response){
          let areaDec = await this._encService.decrypt(occupationArea.AREA);
          let codeDec = await this._encService.decrypt(occupationArea.CODE);

          occupationArea.AREA = `${areaDec} (${codeDec})`;
          this.occupationAreas.push(occupationArea);
        }

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

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

  async getOccupations(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idUser = localStorage.getItem('idusuario')!;
      let occupations: OccupationsListResponse = await lastValueFrom(this._equipmentManagementService.occupationConsult(idUser, 1));

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

      if(!this.hasError){
        let occupationsArr: OccupationsListItem[] = [];
        for(const occupation of occupations.response){
          occupation.FECREG = this._functionsService.orderDate(occupation.FECREG)!;
          if(occupation.FECMOD != null){
            occupation.FECMOD = this._functionsService.orderDate(occupation.FECMOD)!;
          }

          occupationsArr.push(occupation);
        }

        this.dataSource = new MatTableDataSource(occupationsArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

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

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

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  openNewOccupationDialog(action: string, occupation?: OccupationsListItem){
    let dialogRef = this._dialog.open(NewOccupationComponent, {
      width: '320px',
      maxWidth: '320px',
      data: {
        occupationAreas: this.occupationAreas,
        action: action,
        occupation: occupation,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        this.saveOccupation(res, action);
      }
    });
  }

  async saveOccupation(dataStr: string, action: string){
    try{
      let dataArr = dataStr.split('|');
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('area', dataArr[0]);
      formData.append('description', dataArr[1]);

      if(action == 'new'){
        await lastValueFrom(this._equipmentManagementService.occupationRegister(formData));
        this._resourcesService.openSnackBar('La ocupación se registró correctamente.');
      }else{
        let occupationEnc = await this._encService.encrypt(dataArr[2]);
        formData.append('occupation', occupationEnc);
        
        await lastValueFrom(this._equipmentManagementService.occupationUpdate(formData));
        this._resourcesService.openSnackBar('La ocupación se actualizó correctamente.');
      }
      
      this.getOccupations();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (5).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (6).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  confirmDelete(occupation: OccupationsListItem){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '380px',
      maxWidth: '380px',
      data: {
        title: '¡Advertencia!',
        icon: 'warning',
        description: `¿Está seguro de eliminar la ocupación '${occupation.DESCRIPCION}'?`,
        description2: 'Esta acción no se puede deshacer.',
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteOccupation(occupation);
      }
    });
  }

  async deleteOccupation(occupation: OccupationsListItem){
    try{
      let areaArr = occupation.NOMBREAREA.split('(').reverse();
      let area = areaArr[0].replace(')', '');
      let areaEnc = await this._encService.encrypt(area);
      let occupationEnc = await this._encService.encrypt(occupation.OCUPACION);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('area', areaEnc);
      formData.append('occupation', occupationEnc);

      await lastValueFrom(this._equipmentManagementService.occupationDelete(formData));
      this._resourcesService.openSnackBar('La ocupación se eliminó correctamente.');
      
      this.getOccupations();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (7).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (8).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
