import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { ActivatorsListItem, ActivatorsListResponse } from 'src/app/interfaces/counters-activators.interface';
import { CountersActivatorsService } from 'src/app/services/counters-activators.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { ActivatorDetailsComponent } from './activator-details/activator-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-activators-management',
  templateUrl: './activators-management.component.html',
  styleUrls: ['./activators-management.component.css']
})
export class ActivatorsManagementComponent implements OnInit {
  public txtBuscador:string;

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

  orderPriorities: PriorityInterface[];

  dataSource: MatTableDataSource<ActivatorsListItem>;
  displayedColumns = ['IDAC', 'PRIO', 'TIPO', 'IDCO', 'ESTADO', 'ACCIONES'];

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

  constructor(
    private _countersActivatorsService: CountersActivatorsService,
    private _encService: EncService,
    private _systemAdminService: SystemAdminService,
    private _router: Router,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) {
    this.txtBuscador = '';

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

    this.orderPriorities = [];

    this.dataSource = new MatTableDataSource();
  }

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

  public onResize(): void {
    
  }

  async getPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._systemAdminService.getOrderPriorities(idUser, 1));

      if(priorities.error){
        this.hasError = true;
        this.errorStr = priorities.msg;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getActivators();
      }
    }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;
    }
  }

  async getActivators(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      
      let idUser = localStorage.getItem('idusuario')!;
      let activators: ActivatorsListResponse = await lastValueFrom(this._countersActivatorsService.activatorConsult(idUser, 1));

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

      if(!this.hasError){
        let activatorsArr: ActivatorsListItem[] = [];
        for(const activator of activators.response){
          activator.ID_ACTIVADOR = await this._encService.decrypt(activator.ID_ACTIVADOR);
          activator.ID_CONTADOR = await this._encService.decrypt(activator.ID_CONTADOR);

          activatorsArr.push(activator);
        }

        this.dataSource = new MatTableDataSource(activatorsArr);
        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;
    }
  }

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

  getPriorityStr(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "rgb(0, 0, 0)";
    
    let priority = priorityFiltered[0];
    return priority.color;
  }

  async openActivatorForm(type: string, idActivator: string = '-'){
    let idActivatorEnc = await this._encService.encrypt(idActivator);
    this._router.navigate([`sam/COAC/ACTI/GEAC/${type}`], {
      queryParams: {
        idActivator: idActivatorEnc
      }
    })
  }

  async openDetailsDialog(idActivator: string){
    let idActivatorEnc = await this._encService.encrypt(idActivator);
    let dialogRef = this._dialog.open(ActivatorDetailsComponent, {
      width: '480px',
      data: {
        idActivator: idActivatorEnc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      console.log(res);
    });
  }

  openDeleteAlert(idActivator: string){
    let res = this._dialog.open(AlertComponent, {
      width: '420px',
      data: {
        title: '¡Cuidado!',
        icon: 'warning',
        description: `¿Está seguro de eliminar el activador #${idActivator}?`,
        description2: 'Esta acción no se puede deshacer.'
      }
    });

    res.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteActivator(idActivator);
      }
    })
  }

  private async deleteActivator(idActivator: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idActivatorEnc = await this._encService.encrypt(idActivator);

      await lastValueFrom(this._countersActivatorsService.activatorDelete({
        id_user: idUser,
        linea: 1,
        id_activator: idActivatorEnc
      }));

      this._resourcesService.openSnackBar('El activador se eliminó correctamente');
      this.getActivators();
    }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);
      }
    }
  }
}
