import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ProfileResponse, ProfilesResponse } from '../../../interfaces/profiles.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { EncService } from '../../../services/enc.service';
import { FunctionsService } from '../../../services/functions.service';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';

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

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

  dataSource: MatTableDataSource<ProfileResponse>;
  displayedColumns = ['PERFIL', 'USUARIOS', 'ACCIONES'];

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

  constructor(
    private _usersProfilesService: UsersProfilesService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _router: Router,
  ) {
    this.txtBuscador = '';

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

    this.dataSource = new MatTableDataSource();
  }

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

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

      let idUser = localStorage.getItem('idusuario')!;
      let profiles: ProfilesResponse = await lastValueFrom(this._usersProfilesService.getProfiles(idUser, 1));

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

      if(!this.hasError){
        let profilesArr: ProfileResponse[] = [];
        for(const profile of profiles.response){
          profile.IDPERFIL = await this._encService.decrypt(profile.IDPERFIL);
          profile.FECREG = this._functionsService.orderDate(profile.FECREG);

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

          if(profile.ESTADO == 'Activo'){
            profilesArr.push(profile);
          }
        }

        this.dataSource = new MatTableDataSource(profilesArr);
        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 configProfileExportData(idProfile: string){
    let idProfileEnc = await this._encService.encrypt(idProfile);
    this._router.navigate(['sam/PCSA/EDES/data-election-config'], {
      queryParams: {
        data: idProfileEnc,
      }
    });
  }
}
