import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetWorkteams, ResponseDataGetWorkteams } from '../../../interfaces/personal-managment/workteam.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { WorkTeamService } from '../../../services/personal-management/work-team.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { WorkTeamFormComponent } from './work-team-form/work-team-form.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-work-team',
    templateUrl: './work-team.component.html',
    styleUrl: './work-team.component.css',
    standalone: false
})
export class WorkTeamComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<GetWorkteams>;
  public displayedColumns: Array<string>;

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

  constructor(
    public resourcesService: ResourcesService,
    private _workteamService: WorkTeamService,
    private _dialog: MatDialog,
    private _encService: EncService
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.dataSource = new MatTableDataSource<GetWorkteams>();
    this.isLoadingForm = false;
    this.displayedColumns = [ 'WORKTEAM_ID', 'NAME', 'SPECIALITY', 'STATUS', 'ACCIONES' ];
  }

  async ngOnInit() {
    await this.getWorkteams();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  public async getWorkteams() {
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';

      let idUser = localStorage.getItem('idusuario')!;
      let workTeams: ResponseDataGetWorkteams = await lastValueFrom(this._workteamService.getConsultOfWorkteams(idUser, 1));

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

      if(!this.hasError){
        let workTeamsArr: GetWorkteams[] = [];
        for(const team of workTeams.response){
          team.WORKTEAM_ID = await this._encService.decrypt(team.WORKTEAM_ID);
          
          let specialtiesArr: string[] = JSON.parse(team.SPECIALITY);
          let specialtiesStr = "";
          for(const specialtyCode of specialtiesArr){
            let specialtyDec = await this._encService.decrypt(specialtyCode);
            specialtiesStr += `${specialtyDec}, `;
          }

          specialtiesStr = specialtiesStr.substring(0, specialtiesStr.length - 2);
          team.SPECIALITY = specialtiesStr;
          team.SPECIALTY_ARR = specialtiesArr;
          
          workTeamsArr.push(team);
        }

        this.dataSource = new MatTableDataSource(workTeamsArr);
        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.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }
  
  public async openDialog(typeForm: string, element?: GetWorkteams) {
    if (typeForm === 'REG' || typeForm === 'UPD'|| typeForm === 'DET') {
      this._dialog.open(WorkTeamFormComponent, {
        width: '800px',
        maxWidth: '800px',
        disableClose: true,
        data: { 
          action: typeForm, 
          dataElement: element 
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.getWorkteams();
        }
      });
    } else if (typeForm === 'DEL' && element !== undefined) {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Eliminación de Equipo de Trabajo',
          description: '¿Está seguro que desea eliminar al equipo de trabajo?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteWorkteam(element.WORKTEAM_ID);
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
    }
  }

  private async deleteWorkteam(workteamId: string) {
    let idWorkteamEnc = await this._encService.encrypt(`${workteamId}`);
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._workteamService.updateToInactiveStatus({
      WORKTEAM_ID: idWorkteamEnc, 
      id_user: USER,
      linea: LINE, 
    })).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.getWorkteams();
          this.resourcesService.openSnackBar('¡Eliminación exitosa!');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteWorkteam(workteamId);
        }
      }
    );
  }
}
