
package de.ivu.elect.jee.presentation.dynamicform;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.extensions.model.dynaform.DynaFormControl;
import org.primefaces.extensions.model.dynaform.DynaFormModel;


import static de.ivu.elect.jee.presentation.dynamicform.PropertyType.ELECT_5339;

public class AdvancedDynaFormModel extends DynaFormModel {

  private static final long serialVersionUID = 1L;

  private transient AdvancedDynaFormModelRowHandler rowHandler;

  private final Map<String, Boolean> propertyTypesPresent = new ConcurrentHashMap<>();

  private boolean anyPropertyAdded;

  private boolean anyPropertyAddedHiddenOnPageLoad;

  private String id;

  AdvancedDynaFormModel(String id) {
    super();
    this.id = id;
  }

  public String getId() {
    return id;
  }

  public boolean isIdPresent() {
    return StringUtils.isNotBlank(getId());
  }

  /**
   * ELECT-5341
   */
  public boolean isTypePresent(String type) {
    if (type == null) {
      return false;
    }
    return propertyTypesPresent
        .computeIfAbsent(type, missingType -> getControls().stream().anyMatch(dynaFormControl -> missingType.equalsIgnoreCase(dynaFormControl.getType())));
  }

  public boolean isAnyPropertyAdded() {
    return anyPropertyAdded;
  }

  public boolean isAnyPropertyHiddenOnPageLoad() {
    return anyPropertyAddedHiddenOnPageLoad;
  }

  void addProperty(FormBuilderProperty formBuilderProperty, boolean focused) {
    Property property = formBuilderProperty.getProperty();

    anyPropertyAdded = true;

    if (!property.isAccessableOnPageLoad()) {
      anyPropertyAddedHiddenOnPageLoad = true;
    }

    FormData formData = new FormData(property, formBuilderProperty.getFacesMessages(), formBuilderProperty.getFacesValidators(),
        formBuilderProperty.getAttributes(), formBuilderProperty.getValues(),
        focused);

    String dataType = property.getType().getDataType(formBuilderProperty);

    DynaFormControl dynaFormControl = getRowHandler().getRow(formBuilderProperty.getColumn())
        .addControl(formData, dataType, formBuilderProperty.getColSpan(), formBuilderProperty.getRowSpan());

    if (StringUtils.isNotBlank(formBuilderProperty.getKey())) {
      dynaFormControl.setKey(formBuilderProperty.getKey());
    }

  }

  private AdvancedDynaFormModelRowHandler getRowHandler() {
    if (rowHandler == null) {
      rowHandler = new AdvancedDynaFormModelRowHandler(this);
      rowHandler.getRow(0).addControl(null, ELECT_5339.name(), 1, 1); // FIX für ELECT-5339
    }

    return rowHandler;
  }
}
