import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
import { ContractsBySubcontratist, ContractsBySubcontratistResponse, ContractsBySubcontratists } from '../../../../interfaces/personal-managment/subcontratists.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { DownoloadSubcontratistInfo } from '../../../../interfaces/personal-managment/subcontractist.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DOCUMENT } from '@angular/common';
import { ResourcesService } from '../../../../services/resources.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { GdelService } from '../../../../services/gdel.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-contract-history',
    templateUrl: './contract-history.component.html',
    styleUrl: './contract-history.component.css',
    standalone: false
})
export class ContractHistoryComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public idSubcontratist: string;
  public isLoadingForm: boolean;
  public subcontratist: ContractsBySubcontratists;

  public btnSmall: boolean;

  // Para Subcontratistas
  public txtBuscador: string;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<ContractsBySubcontratist>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public infoSubcontracts!: DownoloadSubcontratistInfo;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: ContractsBySubcontratists,
    @Inject(DOCUMENT) private _document: Document,
    private _resourcesService: ResourcesService,
    private _subcontratistService: SubcontratistService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _gdelService: GdelService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.idSubcontratist = "";
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscador = '';
    this.displayedColumns = [
      'CONTRACT_NAME',
      'START_DATE',
      'END_DATE',
      'COST']
    this.dataSource = new MatTableDataSource<any>();
    this.subcontratist = this._data;
  }

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

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

  public async getData() {
    try{
      const USER: string = this._resourcesService.getUser();
      const LINE: number = this._resourcesService.getLineNumber();
      let subContracts: ContractsBySubcontratistResponse = await lastValueFrom(this._subcontratistService.getContractsBySubcontratist(
        this.subcontratist.ID_EMPLEADO, 
        USER,
        LINE
      ));

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

      if(!this.hasError){
        let contracts: ContractsBySubcontratist[] = [];
        for(const contract of subContracts.response){
          contract.START_DATE = this._functionsService.orderDate(contract.START_DATE)!;
          contract.END_DATE = this._functionsService.orderDate(contract.END_DATE)!;

          contracts.push(contract);
        }

        this.dataSource = new MatTableDataSource(contracts);
        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;
    }
  }

  async downloadExcelHistory(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let document = await lastValueFrom(this._subcontratistService.downloadSubcontratistContractsInfoOnExcel(this.subcontratist.ID_EMPLEADO, idUser, 1));
      let documentEnc = await this._encService.encrypt(document.response.fileID);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(documentEnc, idUser, 1));
      let download = this._document.getElementById('download') as HTMLAnchorElement;
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = "";
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async downloadPDFHistory(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let document = await lastValueFrom(this._subcontratistService.downloadSubcontratistContractsInfoOnPdf(this.subcontratist.ID_EMPLEADO, idUser, 1));
      let documentEnc = await this._encService.encrypt(document.response.fileID);
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(documentEnc, idUser, 1));
      let download = this._document.getElementById('download') as HTMLAnchorElement;
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = "";
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
