import { Component } from '@angular/core';
import { MenuFunction, MenuModule, MenuResponse, MenuScreen, MenuSubmodule } from '../../../../interfaces/menu.interface';
import { MatchErrors } from '../../../users-profiles/profiles-admin/new-profile/new-profile.component';
import { FormControl, Validators } from '@angular/forms';
import { EncService } from '../../../../services/enc.service';
import { ModulesService } from '../../../../services/modules.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { ActivatedRoute } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { EmailTemplate, EmailTemplateResponse } from '../../../../interfaces/email-template.interface';
import { ResourcesService } from '../../../../services/resources.service';

@Component({
    selector: 'app-new-template',
    templateUrl: './new-template.component.html',
    styleUrl: './new-template.component.css',
    standalone: false
})
export class NewTemplateComponent {
  isLoading: boolean;
  isNew: boolean;
  hasError: boolean;
  errorStr: string;
  menuModules: MenuModule[];
  emailTemplate: EmailTemplate | null;

  hasBoth: boolean;
  onlySubmenu: boolean;
  onlyFunction: boolean;
  enableScreen: boolean;
  hasFour: boolean;

  menuSubmodules: MenuSubmodule[];
  menuFunctions: MenuFunction[];
  menuFunctionsAux: MenuFunction[];
  menuScreens: MenuScreen[];
  menuScreensAux: MenuScreen[];

  errorMatcher = new MatchErrors();
  templateModule = new FormControl('', [Validators.required]);
  templateSubmodule = new FormControl('', [Validators.required]);
  templateFunction = new FormControl('', [Validators.required]);
  templateScreen = new FormControl('');
  templateMatter = new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(50)]);
  templateBody = new FormControl('', [Validators.required]);

  constructor(
    private _encService: EncService,
    private _modulesService: ModulesService,
    private _sysAdminService: SystemAdminService,
    private _route: ActivatedRoute,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.isNew = true;
    this.hasError = false;
    this.errorStr = "";

    this.hasBoth = false;
    this.onlySubmenu = true;
    this.onlyFunction = false;
    this.enableScreen = false;
    this.hasFour = true;
    this.emailTemplate = null;

    this.menuModules = [];
    this.menuSubmodules = [];
    this.menuFunctions = [];
    this.menuFunctionsAux = [];
    this.menuScreens = [];
    this.menuScreensAux = [];

    this.templateSubmodule.disable();
    this.templateFunction.disable();
    this.templateScreen.disable();
  }

  ngOnInit(): void {
    this._route.queryParams.subscribe(res =>{
      let info = res['info'];
      if(info != undefined && info != null && info != ''){
        this.getTemplate(info)
      }else{
        this.getModules();
      }
    });
  }

  async getTemplate(id: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let emailTemplate: EmailTemplateResponse = await lastValueFrom(this._sysAdminService.getEmailTemplate(id, idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        this.emailTemplate = emailTemplate.response;
        this.getModules();
      }
    }catch(error: any){
      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 getModules(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let menu: MenuResponse = await lastValueFrom(this._modulesService.getMenu(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let menuArr: MenuModule[] = [];
        for(const module of menu.response){
          let idModuleDec = await this._encService.decrypt(module.ID_MODULO);
          module.NOMBRE_MODULO = `${module.NOMBRE_MODULO} (${idModuleDec})`;

          for(const submodule of module.SUBMODULES){
            let idSubmoduleDec = await this._encService.decrypt(submodule.IDSUBMODULO);
            submodule.NOMBRESUBMODULO = `${submodule.NOMBRESUBMODULO} (${idSubmoduleDec})`;

            for(const func of submodule.FUNCIONES){
              let idFunctionDec = await this._encService.decrypt(func.IDFUNCION);
              func.NOMBREFUNCION = `${func.NOMBREFUNCION} (${idFunctionDec})`;

              for(const screen of func.PANTALLAS){
                let idScreenDec = await this._encService.decrypt(screen.IDPANTALLA);
                screen.NOMBREPANTALLA = `${screen.NOMBREPANTALLA} (${idScreenDec})`;
              }
            }
          }

          for(const func of module.MENUS){
            let idFunctionDec = await this._encService.decrypt(func.IDFUNCION);
            func.NOMBREFUNCION = `${func.NOMBREFUNCION} (${idFunctionDec})`;

            for(const screen of func.PANTALLAS){
              let idScreenDec = await this._encService.decrypt(screen.IDPANTALLA);
              screen.NOMBREPANTALLA = `${screen.NOMBREPANTALLA} (${idScreenDec})`;
            }
          }

          menuArr.push(module);
        }
        
        this.menuModules = menuArr;
        if(this.emailTemplate != undefined){
          this.templateSubmodule.enable();
          this.templateFunction.enable();

          let moduleFilt = this.menuModules.filter(item => item.NOMBRE_MODULO.includes(`(${this.emailTemplate!.MODULO})`));
          if(moduleFilt.length < 1){
            this._resourcesService.openSnackBar('El módulo seleccionado en la plantilla es inválido.');
          }else{
            let module = moduleFilt[0];
            this.templateModule.setValue(module.ID_MODULO);
  
            if(module.SUBMODULES.length > 0 && module.MENUS.length > 0){
              this.hasBoth = true;
              this.onlySubmenu = false;
              this.onlyFunction = false;
            }else if(module.SUBMODULES.length > 0 && module.MENUS.length == 0){
              this.hasBoth = false;
              this.onlySubmenu = true;
              this.onlyFunction = false;
            }else{
              this.hasBoth = false;
              this.onlySubmenu = false;
              this.onlyFunction = true;
            }
  
            this.changeSubOptions(module.ID_MODULO);
            if(this.emailTemplate.SUBMODULO != null){
              let submoduleFilt = module.SUBMODULES.filter(item => item.NOMBRESUBMODULO.includes(`(${this.emailTemplate!.SUBMODULO})`));
              this.templateScreen.enable();

              if(submoduleFilt.length > 0){
                this.templateSubmodule.setValue(`${submoduleFilt[0].IDSUBMODULO}##sub`);
                this.changeSec(`${submoduleFilt[0].IDSUBMODULO}##sub`);

                let functionFilt = submoduleFilt[0].FUNCIONES.filter(item => item.NOMBREFUNCION.includes(`(${this.emailTemplate!.FUNCION})`));
                if(functionFilt.length > 0){
                  this.templateFunction.setValue(functionFilt[0].IDFUNCION);
                  this.changeThird(functionFilt[0].IDFUNCION);
      
                  let screenFilt = functionFilt[0].PANTALLAS.filter(item => item.NOMBREPANTALLA.includes(`(${this.emailTemplate!.PANTALLA})`));
                  if(screenFilt.length > 0){
                    this.templateScreen.setValue(screenFilt[0].IDPANTALLA);
                  }else{
                    this._resourcesService.openSnackBar('La pantalla seleccionada en la plantilla es inválida.');
                  }
                }else{
                  this._resourcesService.openSnackBar('La función seleccionada en la plantilla es inválida.');
                }
              }else{
                this._resourcesService.openSnackBar('El submódulo seleccionado en la plantilla es inválido.');
              }
            }else{
              let functionFilt = module.MENUS.filter(item => item.NOMBREFUNCION.includes(`(${this.emailTemplate!.FUNCION})`));
              if(functionFilt.length > 0){
                this.templateSubmodule.setValue(`${functionFilt[0].IDFUNCION}##fun`);
                this.changeSec(`${functionFilt[0].IDFUNCION}##fun`);
    
                let screenFilt = functionFilt[0].PANTALLAS.filter(item => item.NOMBREPANTALLA.includes(`(${this.emailTemplate!.PANTALLA})`));
                if(screenFilt.length > 0){
                  this.templateFunction.setValue(screenFilt[0].IDPANTALLA);
                }
              }else{
                this._resourcesService.openSnackBar('La función seleccionada en la plantilla es inválida.');
              }
            }
  
            this.templateMatter.setValue(this.emailTemplate.ASUNTO);
            this.templateBody.setValue(this.emailTemplate.CUERPO);
          }

          this.isNew = false;
        }
        this.isLoading = false;
      }
    }catch(error: any){
      console.log(error);
      
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (3).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (4).';
      }else{
        this.errorStr = error.error.msg;
      }

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

  changeSubOptions(value: string){
    let moduleFilt = this.menuModules.filter(item => item.ID_MODULO == value);
    if(moduleFilt.length > 0){
      let module = moduleFilt[0];
      
      this.hasBoth = module.SUBMODULES.length > 0 && module.MENUS.length > 0;
      this.onlySubmenu = module.SUBMODULES.length > 0 && module.MENUS.length == 0;
      this.onlyFunction = module.SUBMODULES.length == 0 && module.MENUS.length > 0;
  
      this.enableScreen = this.onlySubmenu;
  
      this.menuSubmodules = module.SUBMODULES;
      this.menuFunctions = module.MENUS;
  
      this.hasFour = this.onlySubmenu || this.hasBoth;
      if(value != ""){
        this.templateSubmodule.enable();
        this.templateSubmodule.setValue('');
      }
  
      this.templateFunction.disable();
      this.templateScreen.disable();
      this.templateFunction.setValue('');
      this.templateScreen.setValue('');
    }else{
      this._resourcesService.openSnackBar('El módulo seleccionado es inválido.');
    }
  }

  changeSec(value: string){
    let valArr = value.split('##');
    let isSub = valArr[1] == 'sub';

    this.templateFunction.setValue('');
    this.templateScreen.setValue('');
    this.templateFunction.enable();
    this.templateScreen.disable();

    if(isSub){
      let subModFilt = this.menuSubmodules.filter(item => item.IDSUBMODULO == valArr[0]);
      if(subModFilt.length > 0){
        let submod = subModFilt[0];
        
        this.hasFour = true;
        this.menuFunctionsAux = submod.FUNCIONES;
      }else{
        this._resourcesService.openSnackBar('El submódulo seleccionado es inválido.');
      }
    }else{
      let functionFilt = this.menuFunctions.filter(item => item.IDFUNCION == valArr[0]);
      if(functionFilt.length > 0){
        let func = functionFilt[0];

        this.hasFour = false;
        this.menuScreensAux = func.PANTALLAS;
      }else{
        this._resourcesService.openSnackBar('La función seleccionada es inválida.');
      }
    }
  }

  changeThird(value: string){
    if(this.hasFour){
      this.templateScreen.enable();
      this.templateScreen.setValue('');

      let functionFilt = this.menuFunctionsAux.filter(item => item.IDFUNCION == value);
      if(functionFilt.length > 0){
        let func = functionFilt[0];
        this.menuScreens = func.PANTALLAS;
      }else{
        this._resourcesService.openSnackBar('La función seleccionada es inválida.');
      }
    }
  }

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

  getSubSelectLabel(): string{
    if(this.hasBoth){
      return "Submódulo / Función";
    }else if(this.onlySubmenu){
      return "Submódulo";
    }else{
      return "Función";
    }
  }

  async saveTemplate(){
    try{
      if(this.templateModule.invalid || this.templateSubmodule.invalid || this.templateFunction.invalid
        || this.templateMatter.invalid || this.templateBody.invalid){
        this._resourcesService.openSnackBar('El formulario de registro contiene errores');

        this.templateModule.markAsTouched();
        this.templateSubmodule.markAsTouched();
        this.templateFunction.markAsTouched();
        this.templateMatter.markAsTouched();
        this.templateBody.markAsTouched();

        return;
      }

      let body = new FormData();
      let idUser = localStorage.getItem('idusuario');
      let idMod = this.templateModule.value;
      let idSub = this.templateSubmodule.value;
      let idFun = this.templateFunction.value;
      let idPan = this.templateScreen.value;

      let subArr = idSub?.split("##");
      let subStr = subArr![0];

      body.append('id_user', idUser!);
      body.append('linea', '1');
      body.append('module', idMod!);

      if(this.hasFour){
        body.append('submodule', subStr!);
        body.append('function', idFun!);
        body.append('screen', idPan!);
      }else{
        body.append('function', subStr!);
        body.append('screen', idFun!);
      }

      body.append('subject', this.templateMatter.value!);
      body.append('body', this.templateBody.value!);
      
      await lastValueFrom(this._sysAdminService.registerEmailTemplate(body));
      this._resourcesService.openSnackBar('La plantilla se registró correctamente.');
      this.goBack(1);
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (5).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (6).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async updateTemplate(){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idTemplate = await this._encService.encrypt(`${this.emailTemplate!.IDPLANTILLA}`);
      let body = new FormData();

      body.append('id_user', idUser!);
      body.append('linea', '1');
      body.append('module', this.templateModule.value!);
      
      let screen = this.templateScreen.value;
      let idSub = this.templateSubmodule.value;
      let subArr = idSub?.split("##");
      let subStr = subArr![0];

      if(screen != undefined && screen != null && screen != ""){
        body.append('submodule', subStr);
        body.append('function', this.templateFunction.value!);
        body.append('screen', this.templateScreen.value!);
      }else{
        body.append('function', subStr);
        body.append('screen', this.templateFunction.value!);
      }

      body.append('subject', this.templateMatter.value!);
      body.append('body', this.templateBody.value!);
      body.append('id_template', idTemplate);

      await lastValueFrom(this._sysAdminService.updateEmailTemplate(body));
      
      this._resourcesService.openSnackBar('La plantilla se actualizó correctamente.');
      this.goBack(1);
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (7).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (8).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
