import { Component, Inject, OnInit } from '@angular/core';
import { ResponseDataSubcontratist, Subcontratist } from '../../../../interfaces/personal-managment/subcontractist.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { ResourcesService } from '../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-subcontratist-details-dialog',
    templateUrl: './subcontratist-details-dialog.component.html',
    styleUrl: './subcontratist-details-dialog.component.css',
    standalone: false
})
export class SubcontratistDetailsDialogComponent implements OnInit {
  idSub: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  subcontratist: Subcontratist | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _subcontratistService: SubcontratistService,
    private _resourcesService: ResourcesService,
  ){
    this.idSub = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.subcontratist = null;
  }

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

  async getData(idSubEnc: string){
    try{
      let idSubDec = await this._encService.decrypt(idSubEnc);
      this.idSub = idSubDec;

      const USER: string = this._resourcesService.getUser();
      const LINE: number = this._resourcesService.getLineNumber();
      let subcontratist: ResponseDataSubcontratist = await lastValueFrom(this._subcontratistService.getSubcontratistById( idSubEnc, USER, LINE));

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

      if(!this.hasError){
        this.subcontratist = subcontratist.response;

        let specialtiesArr: string[] = JSON.parse(this.subcontratist.SPECIALTY);
        let specialtiesStr = "";
        for(const specialty of specialtiesArr){
          let specialtyDec = await this._encService.decrypt(specialty);
          specialtiesStr += `${specialtyDec}, `;
        }

        specialtiesStr = specialtiesStr.substring(0, specialtiesStr.length - 2);
        
        this.subcontratist.SPECIALTY = specialtiesStr;
        this.subcontratist.SPECIALTY_ARR = specialtiesArr;
      }
      
      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;
    }
  }
}
