import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { PreventiveWorkOrdersActive, PreventiveWorkOrdersActiveResponse } from '../../../interfaces/preventive-work-orders-active.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { EncService } from '../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
import { Router } from '@angular/router';
import { SystemAdminService } from '../../../services/system-admin.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-activations-by-activators',
    templateUrl: './activations-by-activators.component.html',
    styleUrl: './activations-by-activators.component.css',
    standalone: false
})
export class ActivationsByActivatorsComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador:string;

  dataSource: MatTableDataSource<PreventiveWorkOrdersActive>;
  displayedColumns = ['ID', 'EQUIP', 'ACTIVADOR', 'PRIORIDAD', 'ACCIONES'];

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

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

  orderPriorities: PriorityInterface[];

  constructor(
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _router: Router,
    private _sysAdminService: SystemAdminService
  ) {
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.orderPriorities = [];
  }

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

  async getOrderPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._sysAdminService.getOrderPriorities(idUser, 1));

      if(priorities.error){
        this.hasError = true;
        this.errorStr = priorities.msg;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getPreventiveWorkOrders();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getPreventiveWorkOrders(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      
      let idUser = localStorage.getItem('idusuario')!;
      let activeOrders: PreventiveWorkOrdersActiveResponse = await lastValueFrom(this._prevMaintService.getActiveWorkOrders(idUser, 1));

      this.hasError = activeOrders.error;
      this.errorStr = activeOrders.msg;

      if(!this.hasError){
        this.dataSource = new MatTableDataSource(activeOrders.response);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }
      
      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  applyFilter(event: any, type: string){
    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();
    }
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "rgb(0, 0, 0)";
    
    let priority = priorityFiltered[0];
    return priority.color;
  }

  getPriorityStr(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  async openActivatorEditor(idOrder: number){
    let idOrderEnc = await this._encService.encrypt(`${idOrder}`);
    this._router.navigate(['sam/GMPR/AOTR/AFDT/editar'], {
      queryParams: {
        data: idOrderEnc,
      },
    });
  }
}
