import { MatSnackBar } from '@angular/material/snack-bar';
import { FunctionsService } from './../../../services/functions.service';
import { EmailServersResponse, EmailServerInfo } from './../../../interfaces/email-servers.interface';
import { SystemAdminService } from './../../../services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { EncService } from './../../../services/enc/enc.service';
import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

@Component({
  selector: 'app-email-config',
  templateUrl: './email-config.component.html',
  styleUrls: ['./email-config.component.css']
})
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;

  public btnSmall: boolean = false;
  public txtBuscador:string;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _functionsService: FunctionsService,
    private _snackBar: MatSnackBar,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.hasServers = false;
    this.errorStr = "";
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this.getServers();
  }

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

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

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

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

      this.hasError = servers.error;
      if(this.hasError){
        this.errorStr = servers.msg;
        this.isLoading = false;
      }else{
        this.dataSource = new MatTableDataSource(servers.response);
        this.hasServers = servers.response.length > 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;
    }
  }

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

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

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

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

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

  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.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg ==  undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  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.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

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