import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ComponentInformationSelect, FormDataPersonality, GetInformationDataSelect, ResponseDataGetInformationDataSelect } from '../../../../interfaces/forms-management/form-management.interface';
import { FormControl, Validators } from '@angular/forms';
import { ResourcesService } from '../../../../services/resources.service';
import { DynamicFormService } from '../../../../services/forms-management/dynamic-form.service';
import { EncService } from '../../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-generate-select',
    templateUrl: './generate-select.component.html',
    styleUrl: './generate-select.component.css',
    standalone: false
})
export class GenerateSelectComponent implements OnInit {
  @Input() public typeForm: 'R' | 'M';
  @Input() public componentSelect: ComponentInformationSelect;

  @Output() public dataValue: EventEmitter<FormControl> = new EventEmitter();

  public formControl: FormControl;
  public require: boolean;
  public disable: boolean;
  public hasPermission: boolean;

  public arrDataInformation: FormDataPersonality[];

  public isLoading: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _dynamicFormService: DynamicFormService,
    private _encService: EncService,
  ) {
    this.typeForm = 'R';
    this.componentSelect = {} as ComponentInformationSelect;
    this.formControl = new FormControl(null);

    this.require = false;
    this.disable = false;
    this.hasPermission = false;

    this.arrDataInformation = [];
    this.isLoading = false;
  }
  
  async ngOnInit() {
    const VALIDATION = await this._setValidators();
    this.formControl = new FormControl({
      value: this.componentSelect.VALOR_DEFECTO,
      disabled: this.disable,
    }, VALIDATION);

    await this._getDataType();

    this.formControl.valueChanges.subscribe((value) => {
      this.dataValue.emit(value);
    });
  }

  private async _setValidators() {
    let arrValidatos: any[] = [];

    if (this.typeForm === 'R') {
      if (this.componentSelect.DESHABILITAR !== null) {
        this.componentSelect.DESHABILITAR.map((element: string) => {
          if (element === 'PARA_REGISTRO') {
            this.disable = true;
          }
        });
      }

      if (this.componentSelect.REQUERIDO !== null) {
        this.componentSelect.REQUERIDO.map((element: string) => {
          if (element === 'PARA_REGISTRO') {
            this.require = true;
            arrValidatos.push(Validators.required);
          }
        });
      }

    } else if (this.typeForm === 'M') {
      if (this.componentSelect.DESHABILITAR !== null) {
        this.componentSelect.DESHABILITAR.map((element: string) => {
          if (element === 'PARA_MODIFICACION') {
            this.disable = true;
          }
        });
      }

      if (this.componentSelect.REQUERIDO !== null) {
        this.componentSelect.REQUERIDO.map((element: string) => {
          if (element === 'PARA_MODIFICACION') {
            this.require = true;
            arrValidatos.push(Validators.required);
          }
        });
      }

    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
    }

    const CURRENT_USER: string = await this.resourcesService.getDecryptUser();
    const PERMISOS: string[] = this.componentSelect.PERMISOS;
    for (const encUser of PERMISOS) {
      const USER: string = await this._encService.decrypt(encUser);
      if (CURRENT_USER === USER) {
        this.hasPermission = true;
      }
    }    

    if (!this.hasPermission) {
      this.disable = true;
    }

    return arrValidatos;
  }

  private async _getDataType() {
    this.isLoading = true;
    const TYPE_SELECT: "CONSULTA_TABLA" | "DATOS_PERSONALIZADOS" = this.componentSelect.TIPO_INFORMACION;
    if (TYPE_SELECT === 'DATOS_PERSONALIZADOS') {
      if (this.componentSelect.DATOS_PERSONALIZABLES !== undefined) {
        this.arrDataInformation = this.componentSelect.DATOS_PERSONALIZABLES;
      } else {
        this.resourcesService.openSnackBar(`Datos no disponibles.`);
      }
    } else if (TYPE_SELECT === 'CONSULTA_TABLA') {
      if (this.componentSelect.OBTENER_DATOS_TABLA !== undefined && this.componentSelect.VALORES_INUTILIZABLES !== undefined) {
        const REMOVE_VALUES: string[] = this.componentSelect.VALORES_INUTILIZABLES;
        const TABLA: string = this.componentSelect.OBTENER_DATOS_TABLA.TABLA;
        const VALOR: string = this.componentSelect.OBTENER_DATOS_TABLA.COLUMNA_VALOR;
        const NOMBRE: string = this.componentSelect.OBTENER_DATOS_TABLA.COLUMNA_NOMBRE;
        const USER: string = this.resourcesService.getUser();
        const LINE: number = this.resourcesService.getLineNumber();
        await lastValueFrom(this._dynamicFormService.getInformationDataSelect(TABLA, VALOR, NOMBRE, USER, LINE)).then(
          (responseData: ResponseDataGetInformationDataSelect) => {
            if (!responseData.error) {
              const DATA_INFORMATION = responseData.response.filter((informationDataSelect: GetInformationDataSelect) => !(REMOVE_VALUES.includes(informationDataSelect.VALOR_CAMPO)) )
              this.arrDataInformation = DATA_INFORMATION;
            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, async (httpErrorResponse: HttpErrorResponse) => {
            let response = this.resourcesService.checkErrors(httpErrorResponse)
            if (response !== null && response.reload) {
              await this._getDataType();
            }
          }
        );
      }
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }
    this.isLoading = false;
  }
}
