import { DialogModule } from '@angular/cdk/dialog';
import { Component, Inject } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { DynamicFormService } from '../../../services/forms-management/dynamic-form.service';
import { EncService } from '../../../services/enc.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-table-management-form',
  standalone: false,
  templateUrl: './table-management-form.component.html',
  styleUrl: './table-management-form.component.css'
})
export class TableManagementFormComponent {

  public formControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: DialogModule,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _dynamicFormService: DynamicFormService,
    private _encService: EncService,
  ) {
    this.formControl = new FormControl('S002V01T', [Validators.required, Validators.minLength(12)])
  }

  public save() {
    this._dialog.open(AlertComponent, {
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de registrar la tabla?`,
        icon: `warning`
      }
    }).afterClosed().subscribe((response) => {
      if (response) {
        this._registerTable();
      }
    });
  }

  private async _registerTable() {
    let table: string = this.formControl.value;
    table = table.toString().trim();

    const ENC_TABLE: string = await this._encService.encrypt(table);

    const REQUEST = {
      TABLA: ENC_TABLE,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    await lastValueFrom(this._dynamicFormService.registerTable(REQUEST)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Registro de tabla exitosa!`);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._registerTable();
        }
      }
    );
  }
}
