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

@Component({
    selector: 'app-failure-log',
    templateUrl: './failure-log.component.html',
    styleUrl: './failure-log.component.css',
    standalone: false
})
export class FailureLogComponent implements OnInit, AfterViewInit {
  public dataSource: MatTableDataSource<FailureLog>;
  public displayedColumns: Array<string>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public isLoading: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _failureAnalysisService: FailureAnalysisService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.dataSource = new MatTableDataSource<FailureLog>();
    this.displayedColumns = ['CODIGO_EQUIPAMIENTO','ESTADO_ACTUAL','CANTIDAD_FALLAS','CLASIFICACION_ACTUAL','ULTIMO_USUARIO','ULTIMA_MODIFICACION','ACTIONS']
    this.isLoading = false;
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.getFailures();
    this.isLoading = false;
  }

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

  public async getFailures() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._failureAnalysisService.getFailure(user, line)).then(
      (responseData: ResponseDataGetFailureLog) => {
        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.getFailures();
        }
      }
    );
    this.isLoading = false;
  }

  public async showHistoryFailureEquipment(codeEquipment: string) {
    const encCodeEquipment: string = await this._encService.encrypt(codeEquipment);
    this._router.navigate([`/sam/ANFA/BIFA/history/${encCodeEquipment}`]);
  }
}
