import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { BroadcastListsItem, BroadcastListsResponse } from '../../../interfaces/control-panel.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { EncService } from '../../../services/enc.service';
import { ControlPanelService } from '../../../services/control-panel.service';
import { FunctionsService } from '../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { BroadcastListFormComponent } from './broadcast-list-form/broadcast-list-form.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-broadcast-lists',
    templateUrl: './broadcast-lists.component.html',
    styleUrl: './broadcast-lists.component.css',
    standalone: false
})
export class BroadcastListsComponent implements OnInit {
  public txtBuscador:string;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  dataSource: MatTableDataSource<BroadcastListsItem>;
  displayedColumns = ['ID', 'NOMBRE', 'ESTADO', 'USUARIO', 'FECHA', 'ACCIONES'];

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

  constructor(
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _controlPanelService: ControlPanelService,
    private _functionsService: FunctionsService,
  ) {
    this.txtBuscador = '';

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

    this.dataSource = new MatTableDataSource();
  }

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

  async getBroadcastLists(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';

      let idUser = localStorage.getItem('idusuario')!;
      let lists: BroadcastListsResponse = await lastValueFrom(this._controlPanelService.getBroadcastLists(idUser, 1));

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

      if(!this.hasError){
        let listsArr: BroadcastListsItem[] = [];
        for(const list of lists.response){
          list.ID_LISTA = await this._encService.decrypt(list.ID_LISTA);
          list.FECREG = this._functionsService.orderDate(list.FECREG);

          if(list.FECMOD != null){
            list.FECMOD = this._functionsService.orderDate(list.FECMOD);
          }

          listsArr.push(list);
        }

        this.dataSource = new MatTableDataSource(listsArr);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }

      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 {

  }

  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 openBroadcastListForm(action: string, idList: string | null){
    let idListEnc = '';
    if(action == 'edit'){
      idListEnc = await this._encService.encrypt(idList!);
    }

    let dialogRef = this._dialog.open(BroadcastListFormComponent, {
      width: '480px',
      maxWidth: '480px',
      disableClose: true,
      data: {
        action: action,
        idList: idListEnc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.saveBroadcastList(action, res);
      }
    });
  }

  private async saveBroadcastList(action: string, dataEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataObj = JSON.parse(dataDec);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('list_name', dataObj.broadcastListName);
      formData.append('related_users', JSON.stringify(dataObj.broadcastListUsers));

      if(action == 'new'){
        await lastValueFrom(this._controlPanelService.registerBroadcastList(formData));
        
        this._resourcesService.openSnackBar('La lista de difusión se creó correctamente.');
        this.getBroadcastLists();
      }else{
        let idListEnc = await this._encService.encrypt(dataObj.idBroadcastList);
        formData.append('id_list', idListEnc);

        await lastValueFrom(this._controlPanelService.updateBroadcastList(formData));
        
        this._resourcesService.openSnackBar('La lista de difusión se actualizó correctamente.');
        this.getBroadcastLists();
      }
    }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);
      }
    }
  }

  openConfirDelete(idList: string){
    let listFilt = this.dataSource.data.filter(item => item.ID_LISTA == idList);
    if(listFilt.length > 0){
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: 'Cuidado',
          icon: 'warning',
          description: `¿Está seguro de eliminar la lista de difusión '${listFilt[0].NOMBRE_LISTA} (${idList})'?`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.deleteBroadcastList(idList);
        }
      });
    }
  }

  private async deleteBroadcastList(idList: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idListEnc = await this._encService.encrypt(idList);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_list', idListEnc);

      await lastValueFrom(this._controlPanelService.deleteBroadcastList(formData));

      this._resourcesService.openSnackBar('La lista de difusión se eliminó correctamente.');
      this.getBroadcastLists();
    }catch(error: any){
      if(error.erorr == 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);
      }
    }
  }
}
