import { Component, Inject, OnInit } from '@angular/core';
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 { SystemAdminService } from '../../../../services/system-admin.service';
import { ResourcesService } from '../../../../services/resources.service';
import { FunctionsService } from '../../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';

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

  activator: Activator | null;
  
  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _countersActivatorsService: CountersActivatorsService,
    private _sysAdminService: SystemAdminService,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.idActivator = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    
    this.activator = null;
  }

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

  async init(){
    this.idActivator = await this._encService.decrypt(this._data.idActivator);
    this.getActivator(this._data.idActivator);
  }

  async getActivator(idActivatorEnc: 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.CONTADOR = await this._encService.decrypt(activator.response.CONTADOR);

        activator.response.FECREG = this._functionsService.orderDate(activator.response.FECREG)!;
        activator.response.FECMOD = activator.response.FECMOD == null ? null : this._functionsService.orderDate(activator.response.FECMOD)!;
        
        this.activator = activator.response;
        this.processActivationCondition();
      }
    }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 processActivationCondition(){
    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(this.activator?.PRIORIDAD == priority.value){
        this.activator.PRIORIDAD_OBJ = priority;
      }
    }

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

    let conditionsObj = JSON.parse(this.activator.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: 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},
    ];
    
    this.activator.CONDICIONES_ARR = conditionsArr;
    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;
    }
  }
}
