import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { ResourcesService } from '../../../../services/resources.service';

@Component({
    selector: 'app-new-panel',
    templateUrl: './new-panel.component.html',
    styleUrl: './new-panel.component.css',
    standalone: false
})
export class NewPanelComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  action: string;
  isNew: boolean;

  panelFormGroup: FormGroup;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<NewPanelComponent>,
    private _resourcesService: ResourcesService,
  ){
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.action = '';
    this.isNew = true;

    this.panelFormGroup = new FormGroup({
      panelID: new FormControl({ value: '', disabled: true }),
      panelName: new FormControl('', [Validators.required, Validators.maxLength(100)]),
      panelOrientation: new FormControl('', Validators.required),
    });
  }

  ngOnInit(): void {
    this.action = this._data.action == 'new' ? 'Registrar' : 'Editar';
    this.isNew = this._data.action == 'new';

    if(!this.isNew){
      this.init();
    }else{
      this.isLoading = false;
    }
  }

  async init(){
    let dataDec = await this._encService.decrypt(this._data.data);
    let dataArr = dataDec.split('|');

    if(dataArr.length != 3){
      this._resourcesService.openSnackBar('La información enviada tiene un formato inválido.');
      return;
    }

    this.panelFormGroup.controls['panelID'].setValue(dataArr[0]);
    this.panelFormGroup.controls['panelName'].setValue(dataArr[1]);
    this.panelFormGroup.controls['panelOrientation'].setValue(dataArr[2].charAt(0));
  }

  async savePanel(){
    let formVal = this.panelFormGroup.getRawValue();
    let formStr = JSON.stringify(formVal);
    let formEnc = await this._encService.encrypt(formStr);

    this._dialogRef.close(formEnc);
  }
}
