import { Component, 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 { CatalogMeasures } from '../../../../interfaces/failure-analysis/catalog-measures.interface';
import { Activator, ActivatorResponse } from '../../../../interfaces/activator.interface';
import { ActivatedRoute } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { CountersActivatorsService } from '../../../../services/counters-activators.service';
import { EncService } from '../../../../services/enc.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { CatalogMeasuresService } from '../../../../services/counters-and-triggers/catalog-measures.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-activator-form',
    templateUrl: './activator-form.component.html',
    styleUrl: './activator-form.component.css',
    standalone: false
})
export class ActivatorFormComponent implements OnInit {
  screenSize: number;
  action: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  isNew: boolean;

  counters: CountersListItem[];
  orderPriorities: PriorityInterface[];
  measures: CatalogMeasures[];
  magnitudes: MagnitudesListItem[];

  activator: Activator | null;

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _countersActivatorsService: CountersActivatorsService,
    private _encService: EncService,
    private _systemAdminService: SystemAdminService,
    private _catalogMeasuresService: CatalogMeasuresService,
  ) {
    this.screenSize = window.innerWidth;
    this.action = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = ""; 
    this.isNew = true;

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

    this.activator = null;
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let idActivatorEnc = params['idActivator'];
      if(idActivatorEnc == null || idActivatorEnc == undefined || idActivatorEnc == ''){
        this._resourcesService.openSnackBar('No se envió información.');
        this.goBack(1);
      }else{
        this.init(idActivatorEnc);
      }
    })
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  async init(idActivatorEnc: string){
    let route = location.href;
    let routeArr = route.split('/').reverse();
    let typeArr = routeArr[0].split('?');
    let type = typeArr[0];

    if(type == 'nuevo'){
      this.isNew = true;
      this.action = "Registrar";

      this.getCounters();
    }else{
      this.isNew = false;
      this.action = "Editar";
      
      this.getActivator(idActivatorEnc);
    }
  }

  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);
          }else if(this.activator != null && this.activator.CONTADOR == idCounterDec){
            countersArr.push(counter);
          }
        }

        this.counters = countersArr;
        this.getPriorities();
      }
    }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 getPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._systemAdminService.getOrderPriorities(idUser, 1));

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

  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);
        
        this.activator = activator.response;
        this.getCounters();
      }
    }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.screenSize = window.innerWidth;
  }

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

      if(this.isNew){
        await lastValueFrom(this._countersActivatorsService.registerActivator(formData));
        this._resourcesService.openSnackBar('El activador se registró correctamente.');
      }else{
        let idActivatorEnc = await this._encService.encrypt(formObj.activatorIDControl);
        formData.append('id_activator', idActivatorEnc);
        
        await lastValueFrom(this._countersActivatorsService.activatorUpdate(formData));
        this._resourcesService.openSnackBar('El activador se actualizó correctamente.');
      }

      this.goBack(1);
    }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);
      }
    }
  }
}
