import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { NewFamilyComponent } from './new-family/new-family.component';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { EquipmentManagementService } from 'src/app/services/equipment-management.service';
import { lastValueFrom } from 'rxjs';
import { FamiliesListItem, FamiliesListResponse } from 'src/app/interfaces/equipment-management.interface';
import { FunctionsService } from 'src/app/services/functions.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Router } from '@angular/router';

@Component({
  selector: 'app-families-management',
  templateUrl: './families-management.component.html',
  styleUrls: ['./families-management.component.css']
})
export class FamiliesManagementComponent implements OnInit {
  public btnSmall: boolean = false;
  public txtBuscador:string;

  dataSource?: MatTableDataSource<FamiliesListItem>;
  displayedColumns = ['CODIGO', 'NOMBRE', 'SUBFAMILIAS', 'ESTADO', 'USRMOD', 'FECMOD', 'ACCIONES'];

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

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

  constructor(
    private _dialog: MatDialog,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _equipmentManagementService: EquipmentManagementService,
    private _functionsService: FunctionsService,
    private _router: Router,
  ) {
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
  }

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

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

  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 openFamilyForm(action: string, family: FamiliesListItem | null = null){
    let dialogRef = this._dialog.open(NewFamilyComponent, {
      width: '480px',
      data: {
        action: action,
        family: family
      }
    });

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

  async getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idUser = localStorage.getItem('idusuario')!;
      let families: FamiliesListResponse = await lastValueFrom(this._equipmentManagementService.familyConsult(idUser, 1));

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

      if(!this.hasError){
        let familiesArr: FamiliesListItem[] = [];
        for(const family of families.response){
          let idEnc = await this._encService.decrypt(family.CODIGOFAMILIA);

          family.CODIGOFAMILIA = idEnc;
          family.FECREG = this._functionsService.orderDate(family.FECREG)!;

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

          familiesArr.push(family);
        }

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

  async saveFamily(dataEnc: string, action: string){
    try{
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataArr = dataDec.split('|');
  
      if(dataArr.length < 2){
        this._resourcesService.openSnackBar('La información ingresada es inválida.');
        return;
      }
  
      let familyCodeEnc = await this._encService.encrypt(dataArr[0]);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('family_code', familyCodeEnc);
      formData.append('family_name', dataArr[1]);

      if(action == 'new'){
        await lastValueFrom(this._equipmentManagementService.familyRegister(formData));
        this._resourcesService.openSnackBar('La familia se registró correctamente.');
      }else{
        await lastValueFrom(this._equipmentManagementService.familyUpdate(formData));
        this._resourcesService.openSnackBar('La familia se actualizó correctamente.');
      }

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

  async deleteFamily(id: string){
    try{
      let codeEnc = await this._encService.encrypt(id);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('family_code', codeEnc);

      await lastValueFrom(this._equipmentManagementService.familyDelete(formData));
      this._resourcesService.openSnackBar('La familia se eliminó correctamente.');

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

  async manageSubfamilies(id: string, name: string){
    let codeEnc = await this._encService.encrypt(`${id}|${name}`);
    this._router.navigate(['sam/GEEQ/DFSU/subfamilias'], {
      queryParams: {
        family: codeEnc,
      }
    });
  }
}
