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';

@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;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _funcService: FunctionsService,
    private _dialog: MatDialog,
    private _snackBar: MatSnackBar,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.templates = [];
    this.txtBuscador = '';
  }

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

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

      this.hasError = templates.error;
      if(this.hasError){
        this.errorStr = templates.msg;
        this.isLoading = false;
      }else{
        this.templates = templates.response;
        this.dataSource = new MatTableDataSource(this.templates);
        this.dataSource.sort = this.sort!;
        this.dataSource.paginator = this.paginator!;
        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.encriptar(`${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.encriptar(`${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;
  }
}
