import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute } from '@angular/router';
import { lastValueFrom } from 'rxjs';;
import { ResponseDataEmployeeContracts } from 'src/app/interfaces/personal-managment/employee.interface';
import { ContractsBySubcontratist, ContractsBySubcontratistResponse, ContractsBySubcontratists } from 'src/app/interfaces/personal-managment/subcontratists.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { FunctionsService } from 'src/app/services/functions.service';
import { EmployeeService } from 'src/app/services/personal-management/employee.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-contracts-history-employee',
  templateUrl: './contracts-history-employee.component.html',
  styleUrls: ['./contracts-history-employee.component.css']
})
export class ContractsHistoryEmployeeComponent implements OnInit {
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public employee: ContractsBySubcontratists;

  public txtBuscador: string;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<ContractsBySubcontratist>;
  public idEmployee: string;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: ContractsBySubcontratists,
    private _employeeService: EmployeeService,
    public _resourcesService: ResourcesService,
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.employee = this._data;

    this.idEmployee = "";
    this.txtBuscador = '';
    this.displayedColumns = [
      'CONTRACT_NAME',
      'START_DATE',
      'END_DATE',
      'CONTRACT_COST']
    this.dataSource = new MatTableDataSource<any>();
  }

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

  public async getData() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let contracts: ContractsBySubcontratistResponse = await lastValueFrom(this._employeeService.getDetailsOfContractsByEmployee(
        this.employee.ID_EMPLOYEE,
        idUser
      ));

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

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

          contractsArr.push(contract);
        }

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

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    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();
    }
  }

}
