import { Component, OnInit, ViewChild } from '@angular/core';
import { EmailTemplate, EmailTemplatesResponse } from '../../../interfaces/email-templates.interface';
import { MatTableDataSource } from '@angular/material/table';
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 { MatDialog } from '@angular/material/dialog';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { ResourcesService } from '../../../services/resources.service';
import { FunctionsService } from '../../../services/functions.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { TemplatesVisorComponent } from './templates-visor/templates-visor.component';

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

  dataSource?: MatTableDataSource<EmailTemplate>;
  displayedColumns = ['ID', 'MOD', 'SUB', 'FUN', 'PAN', 'ASUNTO', 'ESTADO', 'ULMOD', 'FEMOD', 'ACCIONES'];

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

  btnSmall: boolean = false;
  txtBuscador:string;

  templatesHistoryEnabled: boolean;
  regEditTemplateEnabled: boolean;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _dialog: MatDialog,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.templates = [];
    this.txtBuscador = '';
    this.templatesHistoryEnabled = true;
    this.regEditTemplateEnabled = true;
  }

  ngOnInit(): void {
    this.getTemplates();
    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 == 'S002V01F08CPCE');
              if(funPerm.length > 0){
                let templatesHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01HIPL');
                if(templatesHistoryEnabled.length > 0){
                  this.templatesHistoryEnabled = templatesHistoryEnabled[0].access > 0;
                }

                let regEditTemplateEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02NPEP');
                if(regEditTemplateEnabled.length > 0){
                  this.regEditTemplateEnabled = regEditTemplateEnabled[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 getTemplates(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario')!;
      let templates: EmailTemplatesResponse = await lastValueFrom(this._sysAdminService.getEmailTemplates(idUser, 1));

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

      if(!this.hasError){
        this.templates = templates.response;
        this.dataSource = new MatTableDataSource(this.templates);
        this.dataSource.sort = this.sort!;
        this.dataSource.paginator = this.paginator!;

        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 == 'S002V01F08CPCE')[0];

        this.templatesHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01HIPL')[0].access > 0;
        this.regEditTemplateEnabled = funPerm.children.filter(item => item.id == 'S002V01P02NPEP')[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.msg;
      }

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

  registerTemplate(){
    this._router.navigate(['sam/ADSI/CPCE/nuevo']);
  }

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

  openTemplatesVisor(subject: string, body: string){
    this._dialog.open(TemplatesVisorComponent, {
      data: {
        subject: subject,
        body: body,
      }
    });
  }

  async updateTemplate(id: number){
    let idEnc = await this._encService.encrypt(`${id}`);
    this._router.navigate(['sam/ADSI/CPCE/editar'], {
      queryParams: {
        info: idEnc,
      }
    });
  }

  async deleteTemplate(id: number){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idTemplate = await this._encService.encrypt(`${id}`);
      let body = new FormData();

      body.append('id_user', idUser!);
      body.append('linea', '1');
      body.append('id_template', idTemplate);

      await lastValueFrom(this._sysAdminService.deleteEmailTemplate(body));
      
      this._resourcesService.openSnackBar('La plantilla se eliminó correctamente.');
      this.errorStr = "";
      this.hasError = false;
      this.isLoading = true;
      this.getTemplates();
    }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);
      }
    }
  }
}
