import { Component, Inject, 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 { DOCUMENT } from '@angular/common';
import { EncService } from '../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { FunctionsService } from '../../../services/functions.service';
import { GdelService } from '../../../services/gdel.service';
import { lastValueFrom } from 'rxjs';
import { ResourcesService } from '../../../services/resources.service';
import { apiTemp } from '../../../../environments/environment.prod';

@Component({
    selector: 'app-extract-maintenance-plan',
    templateUrl: './extract-maintenance-plan.component.html',
    styleUrl: './extract-maintenance-plan.component.css',
    standalone: false
})
export class ExtractMaintenancePlanComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador:string;

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

  dataSource: MatTableDataSource<PreventiveWorkOrdersActive>;
  displayedColumns = ['ID', 'EQUIP', 'FECINI', 'FECFIN', 'TIEEST', 'TIETOT', 'ACTI', 'PRIO', 'ACCIONES'];

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

  priorities: PriorityInterface[];
  extractEnabled: boolean;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _sysAdminService: SystemAdminService,
    private _funcService: FunctionsService,
    private _docManageService: GdelService,
    private _resourcesService: ResourcesService,
  ) {
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';

    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.dataSource = new MatTableDataSource();
    this.priorities = [];
    this.extractEnabled = true;
  }

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

  async getPriorities(){
    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.priorities = priorities.response.order_priorities;
        this.getActiveOrders();
      }
    }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 getActiveOrders(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let orders: PreventiveWorkOrdersActiveResponse = await lastValueFrom(this._prevMaintService.getActiveWorkOrders(idUser, 1));

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

      if(!this.hasError){
        this.dataSource = new MatTableDataSource(orders.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();
    }
  }

  getDateStr(dateTimeStr: string): string{
    let dateTimeArr = dateTimeStr.split(' ');
    if(dateTimeArr[0] == '0001-01-01'){
      return '-';
    }else{
      return this._funcService.orderDate(dateTimeStr)!;
    }
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.priorities.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.priorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  async extractMaintenancePlan(idOrder: number){
    try{
      this._resourcesService.openSnackBar('Generando PDF...');
      this.extractEnabled = false;

      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${idOrder}`);
      let maintenancePlan = await lastValueFrom(this._prevMaintService.extractMaintenancePlan(
        idOrderEnc,
        idUser,
        1
      ));

      let idFileEnc = await this._encService.encrypt(maintenancePlan.response.fileID);
      let download = this._document.getElementById(`download`) as HTMLAnchorElement;
      let downloadToken = await lastValueFrom(this._docManageService.getDownloadToken(
        idFileEnc,
        idUser,
        1
      ));

      download.href = `${apiTemp}download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = maintenancePlan.response.fileID;
      download.click();

      this.extractEnabled = true;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      
      this.extractEnabled = true;
    }
  }

  async getFileToMSProject(idOrder: number){
    try{
      this._resourcesService.openSnackBar('Generando archivo...');
      this.extractEnabled = false;

      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${idOrder}`);
      let projectFile = await lastValueFrom(this._prevMaintService.getFileToMSProject(
        idOrderEnc,
        idUser,
        1
      ));

      let idFileEnc = await this._encService.encrypt(projectFile.response.fileID);
      let download = this._document.getElementById(`download`) as HTMLAnchorElement;

      let downloadToken = await lastValueFrom(this._docManageService.getDownloadToken(
        idFileEnc,
        idUser,
        1
      ));

      download.href = `${apiTemp}download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = projectFile.response.fileID;
      download.click();

      this.extractEnabled = true;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      
      this.extractEnabled = true;
    }
  }
}
