import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ComponentInformationCheckbox } from '../../../../interfaces/forms-management/form-management.interface';
import { FormControl } from '@angular/forms';
import { ResourcesService } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';

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

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

  public formControl: FormControl;
  public disable: boolean;
  public hasPermission: boolean;
  
  constructor(
    public resourcesService: ResourcesService,
    private _encService: EncService,
  ) {

    this.typeForm = 'R';
    this.componentCheckbox = {} as ComponentInformationCheckbox;

    this.formControl = new FormControl(null);
    this.disable = false;
    this.hasPermission = false;

  }
  
  async ngOnInit() {
    const VALIDATION = await this._setValidators();

    this.formControl = new FormControl({
      value: this.componentCheckbox.VALOR_DEFECTO,
      disabled: this.disable,
    }, VALIDATION);

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

  private async _setValidators() {

    let arrValidatos: any[] = [];

    if (this.typeForm === 'R') {
      if (this.componentCheckbox.DESHABILITAR !== null) {
        this.componentCheckbox.DESHABILITAR.map((element: string) => {
          if (element === 'PARA_REGISTRO') {
            this.disable = true;
          }
        });
      }
    } else if (this.typeForm === 'M') {
      if (this.componentCheckbox.DESHABILITAR !== null) {
        this.componentCheckbox.DESHABILITAR.map((element: string) => {
          if (element === 'PARA_MODIFICACION') {
            this.disable = true;
          }
        });
      }
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
    }

    const CURRENT_USER: string = await this.resourcesService.getDecryptUser();
    const PERMISOS: string[] = this.componentCheckbox.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;

  }
}
