import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { EncService } from '../../../../services/enc.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { FunctionsService } from '../../../../services/functions.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { WebServicesResponse } from '../../../../interfaces/web-services.interface';
import { Permissions } from '../../../../interfaces/permissions.interface';
import { RegisterServiceComponent } from './register-service/register-service.component';

@Component({
    selector: 'app-web-service-admin',
    templateUrl: './web-service-admin.component.html',
    styleUrl: './web-service-admin.component.css',
    standalone: false
})
export class WebServiceAdminComponent implements OnInit {
  public btnSmall: boolean;
  public txtBuscador: string;
  public dataSource: MatTableDataSource<any>;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  displayedColumns: string[] =  ['ID', 'URL', 'DESCRIPCION', 'VINCULOS', 'ESTATUS', 'USUARIO', 'FECHA', 'ACCIONES'];

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

  regEditWebServiceEnabled: boolean;

  constructor(
    private _dialog: MatDialog,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _router: Router,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.btnSmall = false;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();

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

  ngOnInit(): void {
    this.getData();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F06ASWA');
              if(funPerm.length > 0){
                let regEditWebServiceEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P07RESW');
                if(regEditWebServiceEnabled.length > 0){
                  this.regEditWebServiceEnabled = regEditWebServiceEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let webServices: WebServicesResponse = await lastValueFrom(this._sysAdminService.getWebServices(idUser, 1));

      this.dataSource = new MatTableDataSource(webServices.response);
      this.dataSource.paginator = this.paginator!;
      this.dataSource.sort = this.sort!;

      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.decrypt(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);

      let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
      let funPerm = modPerm.children.filter(item => item.id == 'S002V01F06ASWA')[0];

      this.regEditWebServiceEnabled = funPerm.children.filter(item => item.id == 'S002V01P07RESW')[0].access > 0;

      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;
      }
    }
  }
  
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }
  
  public applyFilter(event: any, type: string):void {
    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();
    }
  }

  openRegister(type: string, id: number | null = null, url: string | null = null, desc: string | null = null){
    let dialogRef = this._dialog.open(RegisterServiceComponent, {
      width: '480px',
      data: {
        type: type,
        url: url,
        desc: desc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != "" && res != null && res != undefined){
        if(type == 'new'){
          this.registerWebService(res);
        }else{
          let infoArr = res.split('|');
          this.updateWebService(id!, infoArr[0], infoArr[1]);
        }
      }
    })
  }

  async registerWebService(data: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let dataArr = data.split('|');

      if(dataArr.length != 2){
        this._resourcesService.openSnackBar('La información registrada no tiene un formato correcto.');
      }else{
        let formData = new FormData();

        formData.append('id_user', idUser!);
        formData.append('linea', '1');
        formData.append('url', dataArr[0]);
        formData.append('description', dataArr[1]);

        await lastValueFrom(this._sysAdminService.registerWebService(formData));

        this._resourcesService.openSnackBar('El servicio web se registró 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 updateWebService(id: number, url: string, desc: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idEnc = await this._encService.encrypt(`${id}`);
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_web_service', idEnc);
      formData.append('url', url);
      formData.append('description', desc);

      await lastValueFrom(this._sysAdminService.updateWebService(formData));

      this._resourcesService.openSnackBar('El servicio web 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);
      }
    }
  }

  getUser(usre: string, usmo: string | null): string{
    if(usmo == null){
      return usre;
    }else{
      return usmo;
    }
  }

  getDate(fere: string, femo: string | null): string{
    if(femo == null){
      return this.orderDate(fere);
    }else{
      return this.orderDate(femo);
    }
  }

  orderDate(date: string): string{
    return this._functionsService.orderDate(date)!;
  }

  async changeWSstatus(id: number, currentStatus: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idEnc = await this._encService.encrypt(`${id}`);
      let newStatus = currentStatus == 'Activo' ? 'Inactivo' : 'Activo';
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_web_service', idEnc);
      formData.append('status', newStatus);

      await lastValueFrom(this._sysAdminService.changeWSstatus(formData));
      
      this._resourcesService.openSnackBar('El estado del servicio web 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);
      }
    }
  }
}
