import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { DataDialogValidateForm, InformationValidate } from '../../../interfaces/forms-management/form-management.interface';
import { ResourcesService } from '../../../services/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-validate-where',
  standalone: false,
  templateUrl: './validate-where.component.html',
  styleUrl: './validate-where.component.css'
})
export class ValidateWhereComponent implements OnInit {

  public formGroup: FormGroup;
  public isLoading: boolean;

  public DATA_TABLES: string[];
  public arrColumns: string[];

  constructor (
    @Inject(MAT_DIALOG_DATA) public dataValidate: DataDialogValidateForm,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<false | InformationValidate>,
  ) {
    this.formGroup = this._createFormGroup();
    this.isLoading = false;

    this.DATA_TABLES = dataValidate.TABLES;
    this.arrColumns = [];
  }
  
  ngOnInit(): void {
    this.formGroup.controls['TABLE_VALIDATE'].valueChanges.subscribe((table) => {
      if (table === null || table === undefined || table === '') {
        this.resourcesService.openSnackBar(`El valor del campo Tablas no es correcto.`);
        return;
      }

      const CODE_TABLE: string = table.substring(8, 12);
      const COLUMNS: string[] = this.dataValidate.COLUMNS.filter((column: string) => column.substring(0, 4) === CODE_TABLE);
      this.arrColumns = COLUMNS;
      if (this.arrColumns.length > 0) {
        this.formGroup.controls['COLUMN_VALIDATE'].enable();
      } else {
        this.formGroup.controls['COLUMN_VALIDATE'].disable();
      }
      
    })
  }

  private _createFormGroup(): FormGroup {
    return new FormGroup({
      TABLE_VALIDATE: new FormControl(null, Validators.required),
      COLUMN_VALIDATE: new FormControl({value: null, disabled: true}, Validators.required),
    });
  }

  public save() {
    this._dialog.open(AlertComponent, {
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de registrar la validación?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe((response) => {
      if (response) {
        const TABLE_VALIDATE: string = this.formGroup.controls['TABLE_VALIDATE'].value;
        const COLUMN_VALIDATE: string[] = this.formGroup.controls['COLUMN_VALIDATE'].value;
        
        const INFO_VALIDATE: InformationValidate = {
          TABLA: TABLE_VALIDATE,
          COLUMNAS: COLUMN_VALIDATE,
        }
        
        this._dialogRef.close(INFO_VALIDATE);
      }
    })
  }
}
