import { Component, Inject, OnInit } from '@angular/core';
import { CountersListItem, CountersListResponse, MagnitudesListItem, MagnitudesListResponse } from '../../../../interfaces/counters-activators.interface';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { EncService } from '../../../../services/enc.service';
import { CountersActivatorsService } from '../../../../services/counters-activators.service';
import { ResourcesService } from '../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-activator-dialog',
    templateUrl: './activator-dialog.component.html',
    styleUrl: './activator-dialog.component.css',
    standalone: false
})
export class ActivatorDialogComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  activatorType: string;
  
  counters: CountersListItem[];
  orderPriorities: PriorityInterface[];
  magnitudes: MagnitudesListItem[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _systemAdminService: SystemAdminService,
    private _encService: EncService,
    private _countersActivatorsService: CountersActivatorsService,
    private _dialogRef: MatDialogRef<ActivatorDialogComponent>,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.activatorType = '';

    this.counters = [];
    this.orderPriorities = [];
    this.magnitudes = [];
  }

  ngOnInit(): void {
    this.activatorType = this._data.activatorType;
    this.getCounters();
  }

  async getCounters(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let counters: CountersListResponse = await lastValueFrom(this._countersActivatorsService.counterConsult(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let countersArr: CountersListItem[] = [];
        for(const counter of counters.response){
          let idCounterDec = await this._encService.decrypt(counter.ID_CONTADOR);
          counter.ID_CONTADOR = idCounterDec;

          if(!counter.TIENE_ACTIVADOR && counter.ESTADO == 'Activo'){
            countersArr.push(counter);
          }
        }

        this.counters = countersArr;
        this.getPriorities();
      }
    }catch(error: any){
      console.log(error);
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

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

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

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

      if(priorities.error){
        this.errorStr = priorities.msg;
        this.hasError = true;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getMagnitudes();
      }
    }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 getMagnitudes(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let magnitudes: MagnitudesListResponse = await lastValueFrom(this._systemAdminService.getMagnitudes(idUser, 1));

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

      if(!this.hasError){
        let magnitudesArr: MagnitudesListItem[] = [];
        for(const magnitude of magnitudes.response){
          let idDec = await this._encService.decrypt(magnitude.ID_MAGNITUD);
          magnitude.MAGNITUD = `${magnitude.MAGNITUD} (${idDec})`;
          
          if(magnitude.ESTADO == 'Activo'){
            magnitudesArr.push(magnitude);
          }
        }
        
        this.magnitudes = magnitudesArr;
      }

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

  closeDialog(_: string){
    this._dialogRef.close();
  }

  async saveActivator(event: string){
    try{
      let formDec = await this._encService.decrypt(event);
      let formObj = JSON.parse(formDec);
      let formData = new FormData();
      let idUser = localStorage.getItem('idusuario')!;
      let counterEnc = await this._encService.encrypt(formObj.counterControl)

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('priority', formObj.priorityControl);
      formData.append('type', formObj.activatorTypeControl);
      formData.append('counter', counterEnc);

      switch(formObj.activatorTypeControl){
        case 'CA':
          let confObjCA = {
            startDate: formObj.startDateControl,
            startHour: formObj.startHourControl,
            repeat: formObj.repeatControl,
            customRepeat: formObj.customValue,
            color: formObj.colorPickerControl,
          };

          formData.append('condition', JSON.stringify(confObjCA));
        break;
        case 'SI':
          let symptomArr = formObj.symptomControl.split('(').reverse();
          let symptomStr = symptomArr[0].replace(')', '');
          let symptomEnc = await this._encService.encrypt(symptomStr);

          let confObjSI = {
            sign: symptomEnc,
            startDate: formObj.startDateControl,
            startHour: formObj.startHourControl,
            repeat: formObj.repeatControl,
            customRepeat: formObj.customValue,
            color: formObj.colorPickerControl,
          };

          formData.append('condition', JSON.stringify(confObjSI));
        break;
        case 'ME':
          let confObjME = {
            minValue: formObj.minValueControl,
            maxValue: formObj.maxValueControl,
            magnitude: formObj.magnitudeControl,
            customMagnitude: '',
            unit: formObj.unitControl,
            customUnit: '',
            color: formObj.colorPickerControl,
          };

          formData.append('condition', JSON.stringify(confObjME));
        break;
        case 'VA':
          let confObjVA = {
            comparison: formObj.comparisonControl,
            limitValue: formObj.limitValueControl,
            magnitude: formObj.magnitudeControl,
            customMagnitude: '',
            unit: formObj.unitControl,
            customUnit: '',
            color: formObj.colorPickerControl,
          };

          formData.append('condition', JSON.stringify(confObjVA));
        break;
        default:
          this._resourcesService.openSnackBar('El tipo de activador seleccionado es inválido.');
          return;
        break;
      }

      let res = await lastValueFrom(this._countersActivatorsService.registerActivator(formData));
      
      this._resourcesService.openSnackBar('El activador se registró correctamente.');
      this._dialogRef.close(res.response.IDCONT);
    }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 );
      }
    }
  }
}
