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

@Component({
  selector: 'app-token-generator',
  templateUrl: './token-generator.component.html',
  styleUrls: ['./token-generator.component.css']
})
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 _snackBar: MatSnackBar,
    private _formBuilder: FormBuilder,
    private _dialogRef: MatDialogRef<TokenGeneratorComponent>
  ) { 
    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 shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let scadaList: SCADAList = await lastValueFrom(this._sysAdminService.getSCADAList(shortEnc.response.encrypted, 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;
      }
    }
  }

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

  async generateToken(){
    try{
      let idUser = localStorage.getItem('idusuario');
      if(this.idSCADA == "" || this.tokenDescription == ""){
        this.openSnackBar('Aún no se han rellenado todos los campos obligatorios.');
      }else{
        let scadaEnc = await this._encService.encriptar(`${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.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }
}
