import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { SCADA, SCADAList } from '../../../../../interfaces/scada-list.interface';
import { EncService } from '../../../../../services/enc.service';
import { SystemAdminService } from '../../../../../services/system-admin.service';
import { MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-token-generator',
    templateUrl: './token-generator.component.html',
    styleUrl: './token-generator.component.css',
    standalone: false
})
export class TokenGeneratorComponent implements OnInit {
  firstFormGroup = this._formBuilder.group({
    scadaID: ['', Validators.required],
    tokenDescription: ['', Validators.required],
  });

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  scadaList: SCADA[];
  idSCADA: string;
  tokenDescription: string;
  generatedToken: string;

  @ViewChild('close') close!: ElementRef;

  constructor(
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _formBuilder: FormBuilder,
    private _dialogRef: MatDialogRef<TokenGeneratorComponent>,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.scadaList = [];
    this.idSCADA = "";
    this.tokenDescription = "";
    this.generatedToken = "";
  }

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

  async getSCADAs(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let scadaList: SCADAList = await lastValueFrom(this._sysAdminService.getSCADAList(idUser, 1));

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

      if(!this.hasError){
        this.scadaList = scadaList.response;
      }
      
      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;
      }
    }
  }

  async generateToken(){
    try{
      let idUser = localStorage.getItem('idusuario');
      if(this.idSCADA == "" || this.tokenDescription == ""){
        this._resourcesService.openSnackBar('Aún no se han rellenado todos los campos obligatorios.');
      }else{
        let scadaEnc = await this._encService.encrypt(`${this.idSCADA}`);
        let formData = new FormData();

        formData.append('id_user', idUser!);
        formData.append('id_scada', scadaEnc);
        formData.append('linea', '1');
        formData.append('descripcion', this.tokenDescription);

        let token = await lastValueFrom(this._sysAdminService.generateSCADAtoken(formData));
        
        this.generatedToken = token.response.token;
        this._dialogRef.close(this.generatedToken);
      }
    }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);
      }
    }
  }
}
