import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, 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, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { GenerateSheetComponent } from 'src/app/components/resources/dialogs/generate-sheet/generate-sheet.component';
import { HistoryFailureEquipment, ResponseDataGetHistoryFailureEquipment } from 'src/app/interfaces/failure-analysis/failure.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { FailureLogService } from 'src/app/services/failure-analysis/failure-log.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-history-failure-equipment',
  templateUrl: './history-failure-equipment.component.html',
  styleUrls: ['./history-failure-equipment.component.css']
})
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 _failureLogService: FailureLogService,
  ) {
    this.dataSource = new MatTableDataSource<HistoryFailureEquipment>();
    this.displayedColumns = [
      'NUMERO_FALLA',
      'NOMBRE_FALLA',
      'NIVEL_CRITICIDAD_FALLA',
      'CAUSA',
      'FECHA_FALLA',
      'REPARABLE',
      'ESTADO_FALLA',
      'USUARIO_REGISTRA',
      'FECHA_REGISTRA',
      'ACTIONS'
    ];

    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);    
    await lastValueFrom(this._failureLogService.getHistoryFailureEquipment(encCodeEquipment)).then(
      (responseData: ResponseDataGetHistoryFailureEquipment) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    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);
    await lastValueFrom(this._failureLogService.generateSheetFailureXLS(encFailureNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }
  private async generateSheetFailurePDF(failureNumber: string) {
    this.isLoadingForm = true;
    const encFailureNumber: string = await this._encService.encrypt(failureNumber);
    await lastValueFrom(this._failureLogService.generateSheetFailurePDF(encFailureNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open(`${ responseData.response.url }`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }
  
}
