import { Permissions } from './../../../interfaces/permissions.interface';
import { MatSnackBar } from '@angular/material/snack-bar';
import { TemplatesVisorComponent } from './templates-visor/templates-visor.component';
import { MatDialog } from '@angular/material/dialog';
import { FunctionsService } from './../../../services/functions.service';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { EmailTemplate, EmailTemplatesResponse } from './../../../interfaces/email-templates.interface';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { lastValueFrom } from 'rxjs';
import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';

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

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

  templatesHistoryEnabled: boolean;
  regEditTemplateEnabled: boolean;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _funcService: FunctionsService,
    private _dialog: MatDialog,
    private _snackBar: MatSnackBar,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService, 
  ) { 
    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) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        try{
          let profile = localStorage.getItem('perfil')!;
          let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesSevice.getProfile(
            profile,
            idUser,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.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;
        }catch(error: any){
          if(error.error == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this.openSnackBar(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;
    }
  }

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

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

  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']);
  }

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

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

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

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