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

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

  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 _snackBar: MatSnackBar,
    private _sysAdminService: SystemAdminService,
    private _route: ActivatedRoute,
  ) { 
    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.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 shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let idShort = await lastValueFrom(this._encService.shortEncrypt(id));

      let emailTemplate: EmailTemplateResponse = await lastValueFrom(this._sysAdminService.getEmailTemplate(idShort.response.encrypted, shortEnc.response.encrypted, 1));

      this.emailTemplate = emailTemplate.response;
      this.getModules();
    }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 getModules(){
    try{
      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));

      let menu: MenuResponse = await lastValueFrom(this._modulesService.getMenu(shortEnc.response.encrypted, 1));

      this.hasError = menu.error;
      if(this.hasError){
        this.errorStr = menu.msg;
        this.isLoading = false;
      }else{
        this.menuModules = menu.response;
        if(this.emailTemplate != undefined){
          this.templateModule.setValue(this.emailTemplate.MODULO);
          this.templateSubmodule.enable();
          this.templateFunction.enable();
          let module = this.menuModules.filter(item => item.IDMODULO == this.emailTemplate?.MODULO)[0];

          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(this.emailTemplate.MODULO);
          if(this.emailTemplate.SUBMODULO != null){
            this.templateScreen.enable();

            this.templateSubmodule.setValue(`${this.emailTemplate.SUBMODULO}##sub`);
            this.changeSec(`${this.emailTemplate.SUBMODULO}##sub`);

            this.templateFunction.setValue(this.emailTemplate.FUNCION);
            this.changeThird(this.emailTemplate.FUNCION);

            this.templateScreen.setValue(this.emailTemplate.PANTALLA);
          }else{
            this.templateSubmodule.setValue(`${this.emailTemplate.FUNCION}##fun`);
            this.changeSec(`${this.emailTemplate.FUNCION}##fun`);

            this.templateFunction.setValue(this.emailTemplate.PANTALLA);
          }

          this.templateMatter.setValue(this.emailTemplate.ASUNTO);
          this.templateBody.setValue(this.emailTemplate.CUERPO);

          this.isNew = false;
        }
        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;
    }
  }

  changeSubOptions(value: string){
    let module = this.menuModules.filter(item => item.IDMODULO == value)[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('');
  }

  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 submod = this.menuSubmodules.filter(item => item.IDSUBMODULO == valArr[0])[0];
      
      this.hasFour = true;
      this.menuFunctionsAux = submod.FUNCIONES;
    }else{
      let func = this.menuFunctions.filter(item => item.IDFUNCION == valArr[0])[0];

      this.hasFour = false;
      this.menuScreensAux = func.PANTALLAS;
    }
  }

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

      let func = this.menuFunctionsAux.filter(item => item.IDFUNCION == value)[0];
      this.menuScreens = func.PANTALLAS;
    }
  }

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

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

  async saveTemplate(){
    try{
      if(this.templateModule.invalid || this.templateSubmodule.invalid || this.templateFunction.invalid
        || this.templateMatter.invalid || this.templateBody.invalid){
        this.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.openSnackBar('La plantilla se registró correctamente.');
      this.goBack(1);
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  async updateTemplate(){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idTemplate = await this._encService.encriptar(`${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.openSnackBar('La plantilla se actualizó correctamente.');
      this.goBack(1);
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500
    })
  }
}
