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';

@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;

  constructor(
    private _dialog: MatDialog,
    private _snackBar: MatSnackBar,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _funcService: FunctionsService,
  ) { 
    this.btnSmall = false;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();

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

  ngOnInit(): void {
    this.getData();
  }
  
  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!;

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