import { Component, OnInit } from '@angular/core';
import { ModuleInterface, ModulesInterface } from '../../../../interfaces/modules.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { EncService } from '../../../../services/enc.service';
import { ModulesService } from '../../../../services/modules.service';
import { ActivatedRoute } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { EmailServerResponse } from '../../../../interfaces/email-server.interface';
import { EmailServersResponse } from '../../../../interfaces/email-servers.interface';
import { ResourcesService } from '../../../../services/resources.service';

@Component({
    selector: 'app-new-email-server',
    templateUrl: './new-email-server.component.html',
    styleUrl: './new-email-server.component.css',
    standalone: false
})
export class NewEmailServerComponent implements OnInit {
  isLoading: boolean;
  isNew: boolean;
  hasError: boolean;
  errorStr: string;
  titleStr: string;

  emailServers: any[];
  modules: ModuleInterface[];
  serverForm: FormGroup;

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

    this.emailServers = [];
    this.modules = [];
    this.serverForm = new FormGroup({
      host: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      priority: new FormControl('', [Validators.required, Validators.min(1), Validators.max(100)]),
      user: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      pass: new FormControl('', [Validators.required, Validators.maxLength(2000)]),
      smtpsec: new FormControl('', [Validators.maxLength(50)]),
      port: new FormControl('', [Validators.required, Validators.maxLength(10)]),
      time: new FormControl('', [Validators.required, Validators.maxLength(3)]),
      smtpaut: new FormControl('', [Validators.required, Validators.maxLength(2)]),
      admport: new FormControl('', [Validators.required]),
    });
  }

  ngOnInit(): void {
    this._router.queryParams.subscribe(res => {
      let data = res['data'];
      if(data != undefined && data != null && data != ""){
        this.isNew = false;
        this.decodeParams(data);
      }else{
        this.getModules();
      }
    });
  }

  async decodeParams(encoded: string){
    let decoded = await this._encService.decrypt(encoded);
    let infoObj = JSON.parse(decoded);

    this.getServerInfo(infoObj.host, infoObj.user);
  }

  async getModules(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let modules: ModulesInterface = await lastValueFrom(this._modulesService.getModules(idUser, 1));

      this.hasError = modules.error;
      if(this.hasError){
        this.errorStr = modules.msg;
        this.isLoading = false;
      }else{
        this.modules = modules.response;
        this.getEmailServers();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }
    }
  }

  async getServerInfo(host: string, user: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;

      let emailServer: EmailServerResponse = await lastValueFrom(this._sysadminService.getEmailServer(
        host, 
        user, 
        idUser, 
        1
      ));

      this.hasError = emailServer.error;
      if(this.hasError){
        this.errorStr = emailServer.msg;
        this.isLoading = false;
      }else{
        let smtpsec = emailServer.response.SEGSMTP == null ? '' : emailServer.response.SEGSMTP;
        let portales = JSON.parse(emailServer.response.PORTALES);

        this.serverForm.controls['host'].setValue(`${emailServer.response.HOST}`);
        this.serverForm.controls['priority'].setValue(`${emailServer.response.PRIORIDAD}`);
        this.serverForm.controls['user'].setValue(`${emailServer.response.USUARIO}`);
        this.serverForm.controls['pass'].setValue(`${emailServer.response.CONTRASENA}`);
        this.serverForm.controls['smtpsec'].setValue(`${smtpsec}`);
        this.serverForm.controls['port'].setValue(`${emailServer.response.PUERTO}`);
        this.serverForm.controls['time'].setValue(`${emailServer.response.TIEMPOESPERA}`);
        this.serverForm.controls['smtpaut'].setValue(`${emailServer.response.AUTSMTP}`);
        this.serverForm.controls['admport'].setValue(portales);

        this.serverForm.controls['host'].disable();
        this.serverForm.controls['user'].disable();

        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 getEmailServers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let emailServers: EmailServersResponse = await lastValueFrom(this._sysadminService.getEmailServers(idUser, 1));
      
      this.hasError = emailServers.error;
      if(this.hasError){
        this.errorStr = emailServers.msg;
        this.isLoading = false;
      }else{
        this.emailServers = emailServers.response;
        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;
    }
  }

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

  getErrorMessage(control: string) {
    switch(control){
      case 'host':
        if(this.serverForm.get('host')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('host')?.hasError('maxlength')) return "La longitud debe ser menor a 50 caracteres.";
      break;
      case 'priority':
        if(this.serverForm.get('priority')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('priority')?.hasError('min')) return "El valor debe ser mayor o igual a 1.";
        if(this.serverForm.get('priority')?.hasError('max')) return "El valor debe ser menor o igual a 100.";
      break;
      case 'user':
        if(this.serverForm.get('user')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('user')?.hasError('maxlength')) return "La longitud debe ser menor a 50 caracteres.";
      break;
      case 'pass':
        if(this.serverForm.get('pass')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('pass')?.hasError('maxlength')) return "La longitud debe ser menor a 2000 caracteres.";
      break;
      case 'smtpsec':
        if(this.serverForm.get('smtpsec')?.hasError('maxlength')) return "La longitud debe ser menor a 50 caracteres.";
      break;
      case 'port':
        if(this.serverForm.get('port')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('port')?.hasError('maxlength')) return "La longitud debe ser menor a 10 caracteres.";
      break;
      case 'time':
        if(this.serverForm.get('time')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('time')?.hasError('maxlength')) return "La longitud debe ser menor a 3 caracteres.";
      break;
      case 'smtpaut':
        if(this.serverForm.get('smtpaut')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.serverForm.get('smtpaut')?.hasError('maxlength')) return "La longitud debe ser menor a 2 caracteres.";
      break;
      case 'admport':
        if(this.serverForm.get('admport')?.hasError('required')) return "Este campo es obligatorio.";
      break;
    }
    
    return "A";
  }

  filterNumberValue(event: any): boolean{
    const charCode = (event.which) ? event.which : event.keyCode;
    if(charCode > 31 && (charCode < 48 || charCode > 57)){
      return false;
    }

    return true;
  }

  async registerEmailServer(){
    try{
      if(this.serverForm.valid){
        let idUser = localStorage.getItem('idusuario');
        let formVal = this.serverForm.getRawValue();
        let body = new FormData();

        body.append('id_user', idUser!);
        body.append('linea', '1');
        body.append('host', formVal.host);
        body.append('priority', `${formVal.priority}`);
        body.append('user', formVal.user);
        body.append('password', formVal.pass);
        body.append('port', formVal.port);
        body.append('timeout', formVal.time);
        body.append('smtpaut', formVal.smtpaut);
        body.append('portals', JSON.stringify(formVal.admport));
        
        if(formVal.smtpsec != ""){
          body.append('smtpsec', formVal.smtpsec);
        }
        
        await lastValueFrom(this._sysadminService.registerEmailServer(body));

        this._resourcesService.openSnackBar('El servidor se guardó correctamente.');
        this.goBack(1);
      }else{
        this.serverForm.markAllAsTouched();
      }
    }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);
      }
    }
  }

  async updateEmailServer(){
    try{
      if(this.serverForm.invalid){
        this.serverForm.markAllAsTouched();
      }else{
        let idUser = localStorage.getItem('idusuario');
        let body = new FormData();
        let formVal = this.serverForm.getRawValue();
        let portals = JSON.stringify(formVal.admport);

        body.append('id_user', idUser!);
        body.append('linea', '1');
        body.append('user', formVal.user);
        body.append('host', formVal.host);
        body.append('priority', formVal.priority);
        body.append('port', formVal.port);
        body.append('password', formVal.pass);
        body.append('timeout', formVal.time);
        body.append('smtpaut', formVal.smtpaut);
        body.append('portals', portals);
        if(formVal.smtpsec != null && formVal.smtpsec != undefined && formVal.smtpsec != ""){
          body.append('smtpsec', formVal.smtpsec);
        }

        await lastValueFrom(this._sysadminService.updateEmailServer(body));

        this._resourcesService.openSnackBar('El registro 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);
      }
    }
  }
}
