import { SystemAdminService } from './../../services/system-admin.service';
import { LoginDataService } from './../../services/login/login-data.service';
import { DetailsAlertComponent } from './../system-admin/maintenance-mode/details-alert/details-alert.component';
import { MatDialog } from '@angular/material/dialog';
import { Permissions } from './../../interfaces/permissions.interface';
import { EncService } from './../../services/enc/enc.service';
import { Router, ActivatedRoute } from '@angular/router';
import { ModulesInterface } from './../../interfaces/modules.interface';
import { lastValueFrom } from 'rxjs';
import { ModulesService } from './../../services/modules.service';
import { Component, OnInit, ElementRef } from '@angular/core';
import { BasicAlertComponent } from '../resources/dialogs/basic-alert/basic-alert.component';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  maintenanceEnabled: boolean;
  errorStr: string;
  modules: string[];
  modulesIDS: string[];
  images: string[];
  username: string;
  modulesEnabled: string[];

  constructor(
    private modulesService: ModulesService, 
    private router: Router,
    private el: ElementRef,
    private _encService: EncService,
    private _activatedRoute: ActivatedRoute,
    private _dialog: MatDialog,
    private _loginDataService: LoginDataService,
    private _sysAdminService: SystemAdminService
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.maintenanceEnabled = false;
    this.errorStr = "";
    this.modules = [];
    this.images = [];
    this.modulesIDS = [];
    this.username = "";
    this.modulesEnabled = [];
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let data = params['data'];

      if(data == undefined || data == null || data == ""){
        this.getModules();
      }else{
        this.decInfo(data);
      }
    });
  }

  async decInfo(data: string){
    let dataDec = await this._encService.desencriptar(data);
    let dataArr = JSON.parse(dataDec);

    this.maintenanceEnabled = dataArr['maintenance'] == 'enabled';
    this.getModules();
  }

  async getModules(){
    try{
      let name = localStorage.getItem('nombre_usuario');
      let nameDec = await this._encService.desencriptar(name!);
      this.username = nameDec;

      let permEnc = localStorage.getItem('permisos');
      let permDec = await this._encService.desencriptar(permEnc!);
      let permissions: Permissions = JSON.parse(permDec);

      /*permissions.permissions.forEach(item => {
        if(item.enabled == 'S' || item.enabled == 'P'){
          this.modulesEnabled.push(item.id);
        }
      });*/
      
      let idEnc = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
      let modules: ModulesInterface = await lastValueFrom(this.modulesService.getModules(shortEnc.response.encrypted, 1));

      if(modules.error){
        this.hasError = true;
        this.isLoading = false;
        this.errorStr = modules.msg;
      }else{
        modules.response.forEach(async (module) => {
          if(this.modulesEnabled.includes(module.IDMODULO)){
            this.modules.push(module.NOMBREMODULO);
            this.modulesIDS.push(module.IDMODULO);
          }
        });
        this.isLoading = false;
      }
    }catch(error: any){
      this.isLoading = false;
      this.hasError = true;

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

  navigate(modID: string){
    let element = this.el.nativeElement.querySelector(`#${modID}`);
    element.classList.add('ripple-effect');
    setTimeout(() => element.classList.remove('ripple-effect'), 350);

    let module = modID.replace("S002V01M", "");
    module = module.substring(2, module.length);
    
    this.router.navigate([`sam/${module}`]);
  }

  openUserDetails(){
    console.log("A");
  }

  verTodos(){
    this.router.navigate([`sam/ADMSIS/USUCON`]);
  }

  deactivateMaintenance(){
    let title = "Justificación de la desactivación";
    let body = "Por favor ingrese la justificación de la solución para la desactivación";

    let dialogRef = this._dialog.open(DetailsAlertComponent, {
      data: {
        title: title,
        body: body,
      },
      disableClose: true,
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result != false){
        this.confirmChange(result);
      }
    });
  }

  confirmChange(msg: string){
    let dialogRef = this._dialog.open(BasicAlertComponent, {
      data: {
        title: 'Modo mantenimiento desactivado',
        body: 'El modo mantenimiento ha sido desactivado, deberá iniciar sesión nuevamente al cerar este cuadro de diálogo.'
      }
    });

    dialogRef.afterClosed().subscribe(async (res) => {
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();
      
      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('justificacion', msg);
      
      await lastValueFrom(this._sysAdminService.deactivateMaintenanceMode(formData));
      this._loginDataService.logout();
    });
  }
}
