import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } 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 { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseDataEmployeeDocuments } from 'src/app/interfaces/personal-managment/employee.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { EmployeeService } from 'src/app/services/personal-management/employee.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-documents-employee',
  templateUrl: './documents-employee.component.html',
  styleUrls: ['./documents-employee.component.css']
})
export class DocumentsEmployeeComponent implements OnInit {

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

  constructor(
    private _employeeService: EmployeeService,
    public _resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService) {
    this.idEmployee = "";
    this.isLoading = false;
    this.txtBuscador = '';
    this.displayedColumns = [
      'DOCUMENT_NAME',
      'ACCIONES']
    this.dataSource = new MatTableDataSource<any>();
  }

  ngOnInit(): void {
    this.idEmployee = this._activatedRoute.snapshot.paramMap.get('id')!;
    this.decript();
  }

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

  private async decript() {
    this.idEmployee = await this._encService.desencriptar(this.idEmployee);
    this.getData();
  }

  public async openDialog(element?: any) {
    this._dialog.open(AlertComponent, {
      data: {
        title: 'Descargar de Documento',
        description: '¿Está seguro que desea descargar el documento?',
        icon: 'warning',
      },
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (result) {
        window.open(element.DOCUMENT_LINK.replace('localhost', '192.168.1.50:8000'))
      }
    });
  }

  public async getData() {
    this.isLoading = true;
    await lastValueFrom(this._employeeService.getDocumentsByEmployee(this.idEmployee)).then(
      (responseData: ResponseDataEmployeeDocuments) => {
        responseData.response.forEach(async element => {
          element.DOCUMENT_LINK = await this._encService.desencriptar(element.DOCUMENT_LINK);
        });
        this.dataSource.data = responseData.response
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    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;
    }
    console.log(filterValue);
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

}
