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

@Component({
  selector: 'app-subcontratist-details-dialog',
  templateUrl: './subcontratist-details-dialog.component.html',
  styleUrls: ['./subcontratist-details-dialog.component.css']
})
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 _snackBar: MatSnackBar,
    private _encService: EncService,
    private _subcontratistService: SubcontratistService,
  ){
    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{
      console.log(idSubEnc);
      
      let idSubDec = await this._encService.decrypt(idSubEnc);
      this.idSub = idSubDec;

      let idUser = localStorage.getItem('idusuario')!;
      let subcontratist: ResponseDataSubcontratist = await lastValueFrom(this._subcontratistService.getSubcontratistById(
        idSubEnc,
        idUser
      ));

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

      if(!this.hasError){
        this.subcontratist = subcontratist.response;
      }
      
      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;
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    })
  }
}
