import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { CatalogFailure, ResponseDataGet } from 'src/app/interfaces/ANFA/catalog-failure.interface';
import { CatalogFailureService } from 'src/app/services/failure-analysis/catalog-failure.service';
import { ResourcesService, ResponseData } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { FailureFormComponent } from './failure-form/failure-form.component';

@Component({
  selector: 'app-catalog-failure',
  templateUrl: './catalog-failure.component.html',
  styleUrls: ['./catalog-failure.component.css']
})
export class CatalogFailureComponent implements OnInit {
  public txtBuscador:string;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public btnSmall: boolean;

  public dataSource: MatTableDataSource<any>;
  public displayedColumns: Array<string>;

  constructor(
    public resourcesService: ResourcesService,
    private _catalogFailureService: CatalogFailureService,
    private _dialog: MatDialog,
  ) {
    this.txtBuscador = '';

    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.dataSource = new MatTableDataSource<any>();
    this.displayedColumns = ['LIFA_IDFA','LIFA_NOFA','LIFA_USRE','LIFA_FERE','LIFA_ESTA','ACTIONS'];
  }

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

  public async getCatalogFailure() {
    await lastValueFrom(this._catalogFailureService.getCatalogFailure()).then(
      (responseData: ResponseDataGet) => {
        this.dataSource.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // 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();
    }
  }

  public openDialog( typeForm: string, element?:CatalogFailure ) {
    if ( typeForm === 'REG' || typeForm === 'UPD' ) {
      this._dialog.open( FailureFormComponent, {
        width: '800px',
        disableClose: true,
        data: { action: typeForm, dataElement: element },
      }).afterClosed().subscribe((result) => {
        if (result === 'EXITO') {
          this.getCatalogFailure();
        }
      });
    } else if ( typeForm === 'DEL' ) {
      this._dialog.open( AlertComponent, {
        data: {
          title: 'Eliminación de Falla',
          description: '¿Está seguro que desea eliminar la falla?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteCatalogFailure(element!.LIFA_IDFA);
        }
      });
    }
  }

  private async deleteCatalogFailure( idFailure: number ) {
    await lastValueFrom(this._catalogFailureService.deleteCatalogFailure({
      ID_FALLA: idFailure,
      NUMERO_LINEA: 1,
      USUARIO: this.resourcesService.getUser()
    })).then(
      (responseData: ResponseData) => {
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
        this.getCatalogFailure();
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }
}
