import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { HistoryFailureEquipment, ResponseDataGetHistoryFailureEquipment } from '../../../../interfaces/failure-analysis/failure.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { FailureAnalysisService } from '../../../../services/failure-analysis/failure-analysis.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { GenerateSheetComponent } from '../../../resources/dialogs/generate-sheet/generate-sheet.component';

@Component({
    selector: 'app-history-failure-equipment',
    templateUrl: './history-failure-equipment.component.html',
    styleUrl: './history-failure-equipment.component.css',
    standalone: false
})
export class HistoryFailureEquipmentComponent implements OnInit, AfterViewInit {
  public dataSource: MatTableDataSource<HistoryFailureEquipment>;
  public displayedColumns: Array<string>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public codeEquipment: string;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _router: Router,
    private _dialog: MatDialog,
    private _activatedRoute: ActivatedRoute,
    private _failureAnalysisService: FailureAnalysisService,
  ) {
    this.dataSource = new MatTableDataSource<HistoryFailureEquipment>();
    this.displayedColumns = [
      'NUMERO_FALLA',
      'NOMBRE_FALLA',
      'NIVEL_CRITICIDAD_FALLA',
      'CAUSA',
      'FECHA_FALLA',
      'REPARABLE',
      'ESTADO_FALLA',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ACCIONES',
    ];

    this.codeEquipment = '';
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;

    const encCodeEquipment = this._activatedRoute.snapshot.paramMap.get('equipment');
    if (encCodeEquipment === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al intentar obtener el código del equipamiento.`);
      this._router.navigate([`/sam/ANFA/BIFA`]);
      return;
    } 

    this.codeEquipment = await this._encService.decrypt(encCodeEquipment);
    await this.getHistoryFailureEquipment();


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

  }

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

  public async getHistoryFailureEquipment() {
    this.isLoading = true;
    const encCodeEquipment = await this._encService.encrypt(this.codeEquipment);   
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber(); 
    await lastValueFrom(this._failureAnalysisService.getHistoryFailureEquipment(encCodeEquipment, user, line)).then(
      (responseData: ResponseDataGetHistoryFailureEquipment) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getHistoryFailureEquipment();
        }
      }
    );
    this.isLoading = false;
  }

  public async viewDetailsHistory(historyFailureEquipment: HistoryFailureEquipment) {
    let encFailureNumber: string = await this._encService.encrypt(historyFailureEquipment.NUMERO_FALLA);
    let encEquipmentCode: string = await this._encService.encrypt(this.codeEquipment);
    this._router.navigate([`/sam/ANFA/BIFA/history-details/${encFailureNumber}/${encEquipmentCode}`]);
  }

  public alert(historyFailureEquipment: HistoryFailureEquipment) {
    this._dialog.open(GenerateSheetComponent, {
      disableClose: true,
      data: {
        title: `Generar Ficha de Fallas y Causas`,
        description: `¿Está seguro de descargar la ficha de fallas?`
      }
    }).afterClosed().subscribe((result) => {
      if (result === 'XLS') {
        this.generateSheetFailureXLS(historyFailureEquipment.NUMERO_FALLA);
      } else if (result === 'PDF') {
        this.generateSheetFailurePDF(historyFailureEquipment.NUMERO_FALLA);
      }
    });
  }

  private async generateSheetFailureXLS(failureNumber: string) {
    this.isLoadingForm = true;
    const encFailureNumber: string = await this._encService.encrypt(failureNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._failureAnalysisService.generateSheetFailureXLS(encFailureNumber, user, line)).then(
      (responseData: ResponseData) => {
        /*if (!responseData.error) {
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }*/
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetFailureXLS(failureNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }
  
  private async generateSheetFailurePDF(failureNumber: string) {
    this.isLoadingForm = true;
    const encFailureNumber: string = await this._encService.encrypt(failureNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._failureAnalysisService.generateSheetFailurePDF(encFailureNumber, user, line)).then(
      (responseData: ResponseData) => {
        /*if (!responseData.error) {
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }*/
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetFailurePDF(failureNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }
}
