import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
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 { WebService, WebServicesResponse } from './../../../../../interfaces/web-services.interface';
import { Component, Inject, OnInit } from '@angular/core';

@Component({
  selector: 'app-asign-web-service',
  templateUrl: './asign-web-service.component.html',
  styleUrls: ['./asign-web-service.component.css']
})
export class AsignWebServiceComponent implements OnInit {
  webServices: WebService[];
  service: number;
  description: string;

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

  constructor(
    private _snackBar: MatSnackBar,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<AsignWebServiceComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
  ) { 
    this.webServices = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.service = 0;
    this.description = "Seleccione un servicio web";
  }

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

  async getData(){
    try{
      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));

      webServices.response.forEach(item => {
        if(item.ESTADO == 'Activo'){
          this.webServices.push(item);
        }
      });

      this.service = parseInt(this.data.webService);
      this.description = this.data.description;
      
      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;
      }
    }
  }

  serviceChange(event: any){
    let service = this.webServices.filter(item => item.IDSERVICIO == event);
    if(service.length > 0){
      let desc = service[0].DESCRIPCION;
      this.description = desc;
    }else{
      this.description = 'El ID del servicio web es inválido';
    }
  }

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

  async saveChanges(){
    try{
      if(this.service == 0){
        this.openSnackBar('Aún no se ha seleccionado ningún servicio web.');
      }else{
        let idUser = localStorage.getItem('idusuario');
        let idSW = await this._encService.encriptar(`${this.service}`);
        let formData = new FormData();

        formData.append('id_user', idUser!);
        formData.append('linea', '1');
        formData.append('key', this.data.key);
        formData.append('id_web_service', idSW);

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

        this.openSnackBar('El servicio web se asignó correctamente.');
        this._dialogRef.close(true);
      }
    }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);
      }
    }
  }
}
