import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { GETBGTService } from 'src/app/services/getb/getbgt/getbgt.service';
import { GETBREService } from 'src/app/services/getb/getbre/getbre.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

export interface ResponseData {
  error: boolean;
  msg: string;
  response: Array<any>;
}

@Component({
  selector: 'app-relations-table',
  templateUrl: './table-dyn-management-relations-table.component.html',
  styleUrls: ['./table-dyn-management-relations-table.component.css'],
})
export class TableDynManagementRelationsTable implements OnInit {
  public formGroup: FormGroup;
  data_table: any = [];
  arr_relationship: any = [];
  colums_table: Array<any> = [];
  colums_inner: Array<any> = [];
  relation_name: string = '';

  constructor(
    public dialogRef: MatDialogRef<any>,
    private _getbgtService: GETBGTService,
    private _resourceService: ResourcesService,
    private _getbreService: GETBREService,

    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.arr_relationship = this.data.arr_relationship;
    this.arr_relationship.push({
      TABLA_RELACION: this.data.main_table?.NOMBRE_TABLA,
    });

    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {
    this.column_relation?.disable();
    this.column_compare?.disable();
  }

  private createFormGroup() {
    return new FormGroup({
      table_principal: new FormControl(Validators.required),
      column_relation: new FormControl(Validators.required),
      join_type: new FormControl(Validators.required),
      operator: new FormControl(Validators.required),
      table_secondary: new FormControl(Validators.required),
      column_compare: new FormControl(Validators.required),
    });
  }

  public async dataRelationship() {
    await lastValueFrom(
      this._getbreService.getOneRelationship(this.data.main_table?.CODIGO_TABLA)
    ).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.arr_relationship = data.response;
          this.arr_relationship.push({
            TABLA_RELACION: this.data.main_table?.CODIGO_TABLA,
          });
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  public async dataColumnsPrimary() {
    this.data_table = [];
    let aux_columns = [];
    aux_columns.push(this.table_principal?.value);
    this.relation_name = this.table_principal?.value;

    await lastValueFrom(
      this._getbgtService.getColumns({ tables: aux_columns })
    ).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.colums_table = data.response[0].columns;
          data.response.length > 0
            ? this.column_relation?.enable()
            : this.column_relation?.disable();
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  public async dataColumnsSecondary() {
    this.data_table = [];
    let aux_columns = [];
    aux_columns.push(this.table_secondary?.value);

    await lastValueFrom(
      this._getbgtService.getColumns({ tables: aux_columns })
    ).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.colums_inner = data.response[0].columns;
          data.response.length > 0
            ? this.column_compare?.enable()
            : this.column_compare?.disable();
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  sendData(dataForm: any) {
    let objResponse = {
      tables: [
        `${this.table_principal?.value}`,
        `${this.table_secondary?.value}`,
      ],
      dataForm: dataForm,
    };

    this.dialogRef.close(objResponse);
  }
  get table_principal() { return this.formGroup.get('table_principal'); }
  get join_type() { return this.formGroup.get('join_type'); }
  get column_relation() { return this.formGroup.get('column_relation'); }
  get table_secondary() { return this.formGroup.get('table_secondary'); }
  get column_compare() { return this.formGroup.get('column_compare'); }
  get ope() { return this.formGroup.get('ope'); }
}
