import { Component, EventEmitter, Input, Output } from '@angular/core';
import { DataFields, FormItems, ResponseInformation } from 'src/app/interfaces/dynamic/dynamic-form.interface';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-dynamic-form-structure',
  templateUrl: './dynamic-form-structure.component.html',
  styleUrls: ['./dynamic-form-structure.component.css']
})
export class DynamicFormStructureComponent {

  @Input() fields: DataFields;
  @Output() dataValue: EventEmitter<string | Array<ResponseInformation>> = new EventEmitter();

  constructor( public resourcesService: ResourcesService ) {
    this.fields = {} as DataFields;
  }

  // Generación de objeto a enviar
  public generateResponse() {
    let isError: boolean = false;
    let arrResponse: Array<ResponseInformation> = [];
    this.fields.form.map((form:FormItems) => {

      if (form.required && form.value === null) {
        isError = true;
      }else{
        arrResponse.push({
          value: form.value.toString().trim(),
          column: form.column,
          required: form.required,
          data_table: form.data_table,
          pattern: form.pattern,
        });
      }
    });

    if (isError) {
      this.resourcesService.openSnackBar('Complete los campos obligatorios');
    }else{
      this.dataValue.emit(arrResponse);
    }
  }

}


