import { Component, Inject, OnInit } from '@angular/core';
import { CounterDetails, CounterDetailsResponse } from '../../../../interfaces/counters-activators.interface';
import { ActivationConditions, Activator, ActivatorResponse } from '../../../../interfaces/activator.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { CountersActivatorsService } from '../../../../services/counters-activators.service';
import { FunctionsService } from '../../../../services/functions.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { ResourcesService } from '../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';

@Component({
    selector: 'app-counter-details',
    templateUrl: './counter-details.component.html',
    styleUrl: './counter-details.component.css',
    standalone: false
})
export class CounterDetailsComponent implements OnInit {
  idCounter: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  includesActivator: boolean;

  counter: CounterDetails | null;
  activator: Activator | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _countersActivatorsService: CountersActivatorsService,
    private _functionsService: FunctionsService,
    private _sysAdminService: SystemAdminService,
    private _resourcesService: ResourcesService,
  ) {
    this.idCounter = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.includesActivator = false;

    this.counter = null;
    this.activator = null;
  }

  ngOnInit(): void {
    this.includesActivator = this._data.includeActivator;
    this.init(this._data.idCounter);
  }

  async init(idCounterEnc: string){
    this.idCounter = await this._encService.decrypt(idCounterEnc);

    if(this.includesActivator){
      this.getActivatorDetails(this._data.idActivator, idCounterEnc);
    }else{
      this.getCounterDetails(idCounterEnc);
    }
  }

  async getActivatorDetails(idActivatorEnc: string, idCounterEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let activator: ActivatorResponse = await lastValueFrom(this._countersActivatorsService.getActivator(idActivatorEnc, idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        activator.response.IDACTIVADOR = await this._encService.decrypt(activator.response.IDACTIVADOR as string);
        activator.response.FECREG = this._functionsService.orderDate(activator.response.FECREG)!;
        activator.response.FECMOD = activator.response.FECMOD == null ? null : this._functionsService.orderDate(activator.response.FECMOD)!;
        
        let priorities = await this.getOrderPriorities();
        if(priorities == false){
          this.errorStr = 'Hubó un error al cargar las prioridades de los activadores.';
          this.hasError = true;
          this.isLoading = false;
    
          return;
        }

        for(const priority of priorities as PriorityInterface[]){
          if(activator.response.PRIORIDAD == priority.value){
            activator.response.PRIORIDAD_OBJ = priority;
          }
        }

        if(activator.response.PRIORIDAD_OBJ == null || activator.response.PRIORIDAD_OBJ == undefined){
          this.errorStr = `La prioridad '${activator.response.PRIORIDAD}' es inválida.`;
          this.hasError = true;
          this.isLoading = true;
          
          return;
        }

        let conditionsObj = JSON.parse(activator.response.CONDICIONES as string);
        let customRepeatStr = conditionsObj.customRepeat == undefined ? undefined : conditionsObj.customRepeat;
        if(customRepeatStr != undefined){
          let customRepeatArr = this._functionsService.activatorCustomRepeat(conditionsObj.customRepeat).split('|');
          customRepeatStr = customRepeatArr.length < 2 ? 'NA' : customRepeatArr[0];
        }

        let conditionsArr: ActivationConditions[] = [
          {key: 'Síntoma', value: conditionsObj.sign},
          {key: 'Fecha y hora de inicio', value: conditionsObj.startDate == undefined ? undefined : this._functionsService.orderDate(`${conditionsObj.startDate} ${conditionsObj.startHour}`)},
          {key: 'Repetición', value: conditionsObj.repeat == undefined ? undefined : this._functionsService.activatorRepeat(conditionsObj.repeat, conditionsObj.startDate)},
          {key: 'Repetición personalizada', value: customRepeatStr},
          {key: 'Valor mínimo', value: conditionsObj.minValue},
          {key: 'Valor máximo', value: conditionsObj.maxValue},
          {key: 'Tipo de comparación', value: conditionsObj.comparison == undefined ? undefined : this._functionsService.activatorComparision(conditionsObj.comparison)},
          {key: 'Valor límite', value: conditionsObj.limitValue},
          {key: 'Magnitud', value: conditionsObj.magnitude},
          {key: 'Unidad', value: conditionsObj.unit},
          {key: 'Color', value: conditionsObj.color},
        ];
    
        activator.response.CONDICIONES_ARR = conditionsArr;

        this.activator = activator.response;
        this.getCounterDetails(idCounterEnc);
      }
    }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 getOrderPriorities(): Promise<PriorityInterface[] | boolean>{
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._sysAdminService.getOrderPriorities(idUser, 1));

      if(priorities.error){
        this._resourcesService.openSnackBar(priorities.msg);
        return false;
      }else{
        return priorities.response.order_priorities as PriorityInterface[];
      }
    }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);
      }

      return false;
    }
  }

  async getCounterDetails(idCounterEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let counter: CounterDetailsResponse = await lastValueFrom(this._countersActivatorsService.counterConsultOnly(idCounterEnc, idUser, 1));

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

      if(!this.hasError){
        let idSCADADec = await this._encService.decrypt(counter.response.ID_SCADA);
        counter.response.SCADA = `${counter.response.SCADA} (${idSCADADec})`;

        let codeDec = await this._encService.decrypt(counter.response.CODIGO_EQUIPAMIENTO);
        counter.response.TIPO_EQUIPAMIENTO = `${codeDec} - ${counter.response.TIPO_EQUIPAMIENTO}`;

        let idDec = await this._encService.decrypt(counter.response.ID_EQUIPAMIENTO);
        counter.response.MODELO_EQUIPAMIENTO = `${counter.response.MODELO_EQUIPAMIENTO} (${idDec})`;
        
        this.counter = counter.response;
      }

      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;
    }
  }

  getTimeUnit(unit: string): string{
    if(unit == 'seg') return 'Segundo(s)';
    else if(unit == 'min') return 'Minuto(s)';
    else if(unit == 'hor') return 'Hora(s)';
    else if(unit == 'dia') return 'Día(s)';
    else return '';
  }

  orderDate(date: string): string{
    return this._functionsService.orderDate(date)!;
  }
}
