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

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

  public formGroup: FormGroup;
  public hasError: boolean;

  public arrTableColumns: GetTableColumns[];

  public dataTypeForm: DataTypeForm;

  constructor(
    @Inject(MAT_DIALOG_DATA) public formColumnsData: FormColumnsData,
    public resourcesService: ResourcesService,
    public _dialog: MatDialog,
    public _dialogRef: MatDialogRef<false, GetTableColumns[]>,
  ) {
    this.formGroup = this._createFormGroup();
    this.hasError = false;

    this.arrTableColumns = formColumnsData.INFO_PERSONALITY;
    this.dataTypeForm = { TYPE_FORM: 'R' };

  }
  
  async ngOnInit() {

    this.formGroup.controls['TABLA'].valueChanges.subscribe((tabla) => {
      if (tabla !== null && tabla !== '' && tabla.length === 12) {
        this.formGroup.controls['COLUMNA_NUEVA'].enable();

      } else {
        this.formGroup.controls['COLUMNA_NUEVA'].disable();
      }
    });

    this.formGroup.controls['COLUMNA_NUEVA'].valueChanges.subscribe((column) => {
      const TABLE_NAME: string = this.formGroup.controls['TABLA'].value;

      if (column !== null && column !== undefined && column.length === 4 && TABLE_NAME !== null) {        
        
        const CODE_COLUMN: string = column.toUpperCase();
        const CODE_TABLE: string = TABLE_NAME.substring(8, 12);

        const COLUMN = `${CODE_TABLE}_${CODE_COLUMN}`;

        const INFO_TABLE: GetTables | undefined = this.formColumnsData.COLUMNS_GENERAL.find((getTables: GetTables) => getTables.NOMBRE_TABLA === TABLE_NAME);
        if (INFO_TABLE !== undefined) {
          for(const DATA_COLUMN of INFO_TABLE.COLUMNS) {
            if (DATA_COLUMN.COLUMN == COLUMN) {
              this.hasError = true;
              this.resourcesService.openSnackBar(`El nombre de la column no se puede repetir con las columnas ya registradas.`);
            } else {
              this.hasError = false;
            }
          }
        } else {
          this.hasError = false;
        }
      } else {
        this.hasError = false;
      }
    });
  }

  private _createFormGroup() {
    return new FormGroup({  
      TABLA: new FormControl(null, Validators.required),
      COLUMNA_NUEVA: new FormControl({ value: null, disabled: true }, [Validators.required, Validators.minLength(4) ]),
      DECRIPCION_COLUMNA: new FormControl(null, Validators.required),
    });
  }

  public codeTable(): string {
    const TABLA: string = this.formGroup.controls['TABLA'].value;
    if (TABLA !== null) {
      const CODE: string = TABLA.substring(8, 12);
      return `${CODE}_`;
    }
    return '-----';
  }

  public addColumn() {
    const TABLE:string = this.formGroup.controls['TABLA'].value;
    if (TABLE === null) {
      return;
    }

    const CODE_COLUMN: string = this.formGroup.controls['COLUMNA_NUEVA'].value;
    if (CODE_COLUMN === null) {
      return;
    }

    const DESCRIPTION_COLUMN: string = this.formGroup.controls['DECRIPCION_COLUMNA'].value;
    if (DESCRIPTION_COLUMN === null) {
      return;
    }

    const CODE_TABLE: string = TABLE.substring(8, 12);
    for (const COLUMNS_GENERAL of this.formColumnsData.COLUMNS_GENERAL) {
      for (const DATA_COLUMN of COLUMNS_GENERAL.COLUMNS) {
        if (DATA_COLUMN.COLUMN === `${CODE_TABLE}_${CODE_COLUMN}`) {
          this.resourcesService.openSnackBar(`La columna ya se encuentra registrada`);
          return;
        }
      }
    }

    const NEW_COLUMN_TABLE: string = `${CODE_TABLE}_${CODE_COLUMN} (personalizado)`;

    for (const TABLE_COLUMNS of this.arrTableColumns) {
      for (const COLUMN of TABLE_COLUMNS.COLUMNS) {
        if (COLUMN.COLUMN === NEW_COLUMN_TABLE) {
          this.resourcesService.openSnackBar(`La columna ya se encuentra registrada`);
          return;
        }
      }
    }

    const INDEX_FILTER: number = this.arrTableColumns.findIndex((tableColumns: GetTableColumns) => tableColumns.TABLA === TABLE);
    if (INDEX_FILTER === -1) {
      const FORM_COLUMNS: FormColumns = {
        COLUMN: NEW_COLUMN_TABLE,
        DESCRIPTION: DESCRIPTION_COLUMN,
      }

      this.arrTableColumns.push({
        TABLA: TABLE,
        COLUMNS: [FORM_COLUMNS],
      });
    } else {
      let arrColumns: FormColumns[] = this.arrTableColumns[INDEX_FILTER].COLUMNS;
      arrColumns.push({
        COLUMN: NEW_COLUMN_TABLE,
        DESCRIPTION: DESCRIPTION_COLUMN,
      });

      this.arrTableColumns[INDEX_FILTER].COLUMNS = arrColumns;
    }
    
    this.formGroup.reset();
    
  }

  public updateColumn() {
    
    if (this.dataTypeForm.INDEX_COLUMN === undefined || this.dataTypeForm.INDEX_TABLE === undefined) {
      return;
    }
    
    const INDEX_TABLE:number = this.dataTypeForm.INDEX_TABLE;
    const INDEX_COLUMN:number = this.dataTypeForm.INDEX_COLUMN;

    if (this.arrTableColumns[INDEX_TABLE] === undefined) {
      this.resourcesService.openSnackBar(`La información de la tabla no existe.`);
      return;
    }

    if (this.arrTableColumns[INDEX_TABLE].COLUMNS[INDEX_COLUMN] === undefined) {
      this.resourcesService.openSnackBar(`La información de la columna no existe.`);
      return;
    }

    const TABLE:string = this.formGroup.controls['TABLA'].value;
    if (TABLE === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener la información del nombre de la tabla.`);
      return;
    }

    const NEW_COLUMN: string = this.formGroup.controls['COLUMNA_NUEVA'].value;
    this.resourcesService.openSnackBar(`Ocurrió un error al obtener la información del nombre de la columna.`);
    if (NEW_COLUMN === null) {
      return;
    }

    const DESCRIPTION_COLUMN: string = this.formGroup.controls['DECRIPCION_COLUMNA'].value;
    if (DESCRIPTION_COLUMN === null) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener la información de la descripción.`);
      return;
    }

    this.arrTableColumns[INDEX_TABLE].TABLA = TABLE;
    this.arrTableColumns[INDEX_TABLE].COLUMNS[INDEX_COLUMN].COLUMN = NEW_COLUMN;
    this.arrTableColumns[INDEX_TABLE].COLUMNS[INDEX_COLUMN].DESCRIPTION = DESCRIPTION_COLUMN;

    this.dataTypeForm.TYPE_FORM = 'R';
    this.dataTypeForm.INDEX_COLUMN = undefined;
    this.dataTypeForm.INDEX_TABLE = undefined;

    this.formGroup.reset();
  }

  public editColumn(idxTable: number, idxColumn: number) {
    const TABLE_COLUMNS: GetTableColumns = this.arrTableColumns[idxTable];
    const TABLE: string = TABLE_COLUMNS.TABLA;
    this.formGroup.controls['TABLA'].setValue(TABLE);
    
    const FORM_COLUMNS:FormColumns = TABLE_COLUMNS.COLUMNS[idxColumn];

    const CODE_COLUMN: string = FORM_COLUMNS.COLUMN.substring(5, 9);
    
    this.formGroup.controls['COLUMNA_NUEVA'].setValue(CODE_COLUMN);
    this.formGroup.controls['DECRIPCION_COLUMNA'].setValue(FORM_COLUMNS.DESCRIPTION);

    this.dataTypeForm.TYPE_FORM = 'M';
    this.dataTypeForm.INDEX_TABLE = idxTable;
    this.dataTypeForm.INDEX_COLUMN = idxColumn;
  }

  public deleteColumn(idxTable: number, idxColumn: number) {
    
    if (this.dataTypeForm.INDEX_COLUMN !== undefined || this.dataTypeForm.INDEX_TABLE !== undefined) {
      return;
    }
    
    const INDEX_TABLE:number = idxTable;
    const INDEX_COLUMN:number = idxColumn;

    const COLUMNS: FormColumns[] = this.arrTableColumns[INDEX_TABLE].COLUMNS.filter((formColumns: FormColumns, indexColumn: number) => indexColumn !== INDEX_COLUMN);
    if (COLUMNS.length === 0) {
      const TABLES: GetTableColumns[] = this.arrTableColumns.filter((tableColumns: GetTableColumns, indexTable: number) => indexTable !== INDEX_TABLE);
      this.arrTableColumns = TABLES;
    } else {
      this.arrTableColumns[INDEX_TABLE].COLUMNS = COLUMNS;
    }    
  }

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