import { Component, OnInit } from '@angular/core';
import { ControlPanelDetails, ControlPanelDetailsResponse, PanelCountersListItem, PanelCountersListResponse, PanelElements } from '../../../../interfaces/control-panel.interface';
import { UserResponse, UsersResponse } from '../../../../interfaces/users.interface';
import { ActivatedRoute } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { ControlPanelService } from '../../../../services/control-panel.service';
import { EncService } from '../../../../services/enc.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-control-panel-preview',
    templateUrl: './control-panel-preview.component.html',
    styleUrl: './control-panel-preview.component.css',
    standalone: false
})
export class ControlPanelPreviewComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  controlPanel: ControlPanelDetails | null;
  panelIndicators: PanelElements[];
  users: UserResponse[];
  countersIndicators: PanelCountersListItem[];

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _controlPanelService: ControlPanelService,
    private _encService: EncService,
    private _usersProfilesService: UsersProfilesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.controlPanel = null;
    this.panelIndicators = [];
    this.users = [];
    this.countersIndicators = [];
  }

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

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

  async getPanel(idPanel: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let panel: ControlPanelDetailsResponse = await lastValueFrom(this._controlPanelService.getPanel(idPanel, idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        panel.response.ID_PANEL = await this._encService.decrypt(panel.response.ID_PANEL);

        let panelIndicators: PanelElements[] = JSON.parse(panel.response.INDICADORES_RELACIONADOS);
        for(const element of panelIndicators){
          element.module = await this._encService.decrypt(element.module);
          element.idElement = await this._encService.decrypt(element.idElement);

          this.panelIndicators.push(element);
        }

        this.controlPanel = panel.response;
        this.getUsers();
      }
    }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 getUsers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let users: UsersResponse = await lastValueFrom(this._usersProfilesService.getUsers(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let idUserDec = await this._encService.decrypt(idUser);
        let usersArr: UserResponse[] = [];

        for(const user of users.response){
          user.IDUSUARIO = await this._encService.decrypt(user.IDUSUARIO);
          if(user.IDUSUARIO != idUserDec){
            usersArr.push(user);
          }
        }

        this.users = usersArr;
        this.getIndicators();
      }
    }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 getIndicators(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let indicators: PanelCountersListResponse = await lastValueFrom(this._controlPanelService.getCountersList(idUser, 1));

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

      if(!this.hasError){
        let countersArr: PanelCountersListItem[] = [];
        for(const counter of indicators.response){
          let idCounterDec = await this._encService.decrypt(counter.ID_CONTADOR);
          counter.ID_CONTADOR = idCounterDec;

          countersArr.push(counter);
        }

        this.countersIndicators = countersArr;
      }

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