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

@Component({
  selector: 'app-web-service-admin',
  templateUrl: './web-service-admin.component.html',
  styleUrls: ['./web-service-admin.component.css']
})
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 _snackBar: MatSnackBar,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _funcService: FunctionsService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService, 
    private _router: Router,
  ) { 
    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) => {
      let shortID = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('idusuario')!));
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(shortID.response.encrypted, shortID.response.encrypted, 1));
      let currentProfile = await this._encService.desencriptar(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.desencriptar(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        try{
          let shortProf = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('perfil')!));
          let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesSevice.getProfile(
            shortProf.response.encrypted,
            shortID.response.encrypted,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.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;
        }catch(error: any){
          if(error.error == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this.openSnackBar(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();
    }
  }

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

      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let webServices: WebServicesResponse = await lastValueFrom(this._sysAdminService.getWebServices(shortEnc.response.encrypted, 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.desencriptar(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;
      }
    }
  }

  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 updateWebService(id: number, url: string, desc: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idEnc = await this._encService.encriptar(`${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.openSnackBar('El servicio web se actualizó correctamente.');
      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

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

      if(dataArr.length != 2){
        this.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.openSnackBar('El servicio web se registró correctamente.');
        this.getData();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    })
  }

  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._funcService.orderDate(date);
  }

  async changeWSstatus(id: number, currentStatus: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idEnc = await this._encService.encriptar(`${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.openSnackBar('El estado del servicio web se actualizó correctamente.');
      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }
}
