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;
  @Input() typeForm: string;
  @Output() dataValue: EventEmitter<string | Array<ResponseInformation>> = new EventEmitter();

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

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

      let requiered = this.typeForm === 'REG' ? form.required_reg : form.required_mod;
      if (requiered && (form.value === null || ( Array.isArray(form.value) && form.value.length === 0))) {
        isError = true;
      }else{

        if (form.tag === 'input' && form.type === 'date' && typeof form.value === 'object' && !Array.isArray(form.value)) {

          let day: number|string = form.value.getDate();
          let month: number|string = form.value.getMonth() + 1;
          let year: number = form.value.getFullYear();

          if (day < 10) {
            day = '0' + day;
          }
          if (month < 10) {
            month = '0' + month;
          }

          arrResponse.push({
            value: `${year}-${month}-${day}`,
            column: form.column,
            required: requiered,
            data_table: form.data_table,
            pattern: form.pattern,
          });
        } else {
          arrResponse.push({
            value: typeof form.value === 'string' ? form.value.toString().trim() : form.value,
            column: form.column,
            required: requiered,
            data_table: form.data_table,
            pattern: form.pattern,
          });
        }

      }
    });

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

  public validatorForm(){
    let isDisabled: boolean = false;
    this.fields.form.map((form:FormItems) => {
      let required = this.typeForm === 'REG' ? form.required_reg : form.required_mod;
      // Se verifica que el campo sea requerido
      if (required && (form.value === null || form.value === '' || ( Array.isArray(form.value) && form.value.length === 0))) {
        isDisabled = true;
      }
      // Se verifica que el pattern tenga valores
      if (form.pattern !== null) {
        // Se tranforma a valores que se puedan tratar
        let dataValidate = new RegExp(form.pattern);
        let dataText:string = typeof form.value === 'string' ? form.value : '';
        // Se realiza la validación respecto al texto colocado
        if (!dataValidate.test(dataText)) {
          // Se ingresa el mensaje del error del formulario
          isDisabled = true;
        }
      }

    });

    return isDisabled;
  }

  public setDataInput(textValue:any, type:string, idInput: string){

    this.fields.form = this.fields.form.map((form:FormItems) => {
      if (form.id === idInput && type === 'date') {

        let arrDate = textValue.toString().split('-');
        let year: number | string = parseInt(arrDate[0]) ;
        let month: number | string = parseInt(arrDate[1]);
        let day: number = parseInt(arrDate[2]);

        textValue = new Date( `${year}-${month}-${day}` );
        form.value = textValue;

      }else if (form.id === idInput && type !== 'date') {
        form.value = textValue;
      }
      return form;
    });
  }
}


