import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { EmailServerInfo, EmailServersResponse } from '../../../interfaces/email-servers.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { FunctionsService } from '../../../services/functions.service';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { ResourcesService } from '../../../services/resources.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';

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

  dataSource?: MatTableDataSource<EmailServerInfo>;
  displayedColumns = ['host', 'usuario', 'prioridad', 'usrreg', 'fecreg', 'usrmod', 'fecmod', 'estado', 'acciones'];

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  btnSmall: boolean = false;
  txtBuscador:string;

  createEmailServerEnabled: boolean;
  emailServersListEnabled: boolean;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _functionsService: FunctionsService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.hasServers = false;
    this.errorStr = "";
    this.txtBuscador = '';
    this.createEmailServerEnabled = true;
    this.emailServersListEnabled = true;
  }

  ngOnInit(): void {
    this.getServers();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F07CCEL');
              if(funPerm.length > 0){
                let createEmailServerEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01CNSC');
                if(createEmailServerEnabled.length > 0){
                  this.createEmailServerEnabled = createEmailServerEnabled[0].access > 0;
                }

                let emailServersListEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02LSCE');
                if(emailServersListEnabled.length > 0){
                  this.emailServersListEnabled = emailServersListEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });
  }

  async getServers(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario')!;
      let servers: EmailServersResponse = await lastValueFrom(this._sysAdminService.getEmailServers(idUser, 1));

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

      if(!this.hasError){
        this.dataSource = new MatTableDataSource(servers.response);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
        this.hasServers = servers.response.length > 0;

        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = await this._encService.decrypt(permissionsEnc!);
        let permissionsArr: Permissions = JSON.parse(permissionsDec);

        let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
        let funPerm = modPerm.children.filter(item => item.id == 'S002V01F07CCEL')[0];

        this.createEmailServerEnabled = funPerm.children.filter(item => item.id == 'S002V01P01CNSC')[0].access > 0;
        this.emailServersListEnabled = funPerm.children.filter(item => item.id == 'S002V01P02LSCE')[0].access > 0;
      }

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

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

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  registerServer(){
    this._router.navigate(['sam/ADSI/CCEL/nuevo'])
  }

  orderDate(date: string){
    return this._functionsService.orderDate(date);
  }

  async editServer(host: string, user: string){
    let hostEnc = await this._encService.encrypt(host);
    let userEnc = await this._encService.encrypt(user);

    let infoStr = JSON.stringify({
      host: hostEnc,
      user: userEnc,
    });

    let infoEnc = await this._encService.encrypt(infoStr);
    this._router.navigate(['sam/ADSI/CCEL/editar'], {
      queryParams: {
        data: infoEnc,
      }
    });
  }

  async deactivateServer(host: string, user: string, state: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let body = new FormData();

      body.append('id_user', idUser!);
      body.append('linea', '1');
      body.append('user', user);
      body.append('host', host);
      body.append('state', state);

      await lastValueFrom(this._sysAdminService.deactivateEmailServer(body));

      this.hasError = false;
      this.errorStr = "";
      this.isLoading = true;

      this.getServers();
    }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 deleteServer(host: string, user: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let body = new FormData();

      body.append('id_user', idUser!);
      body.append('linea', '1');
      body.append('user', user);
      body.append('host', host);

      await lastValueFrom(this._sysAdminService.deleteEmailServer(body));

      this.hasError = false;
      this.errorStr = "";
      this.isLoading = true;

      this.getServers();
    }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);
      }
    }
  }
}
