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 { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { FailureLog, ResponseDataGetFailureLog } 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';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-failure-log',
  templateUrl: './failure-log.component.html',
  styleUrls: ['./failure-log.component.css']
})
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;
  public isLoadingForm: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _failureService: FailureLogService,
    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;
    this.isLoadingForm = false;
  }

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

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

  public async getFailures() {
    this.isLoading = true;
    await lastValueFrom(this._failureService.getFailure()).then(
      (responseData: ResponseDataGetFailureLog) => {
        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 showHistoryFailureEquipment(codeEquipment: string) {
    const encCodeEquipment: string = await this._encService.encrypt(codeEquipment);
    this._router.navigate([`/sam/ANFA/BIFA/history/${encCodeEquipment}`]);
  }
}
