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

import static org.apache.commons.lang3.StringUtils.endsWith;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import de.ivu.elect.jee.faces.StringEmptyToNullConverter;

public abstract class AbstractMaskProperty extends AbstractStringProperty {

  // Cf. org.primefaces:primefaces /META-INF/resources/primefaces/components.js
  private static final String DEFAULT_PRIMEFACES_INPUT_MASK_SLOT_CHAR = "_";

  public static final String DEFAULT_MASK_SLOT_CHAR = DEFAULT_PRIMEFACES_INPUT_MASK_SLOT_CHAR;

  public AbstractMaskProperty() {
    super();
  }

  public abstract String getMask();

  public abstract String getMaskSlotChar();

  @Override
  public PropertyType getDefaultType() {
    return PropertyType.INPUT_MASK;
  }

  @Override
  public Converter getDefaultConverter() {
    return createMaskConverter(getMaskSlotChar());
  }

  public static Converter createMaskConverter(String maskSlotChar) {
    return new StringEmptyToNullConverter() {

      @Override
      public Object getAsObject(FacesContext context, UIComponent component, String value) {
        Object result = super.getAsObject(context, component, value);

        if (result instanceof String) {
          String string = (String) result;

          if (endsWith(string, maskSlotChar)) {
            result = string.replace(maskSlotChar, "");
          }
        }

        return result;
      }
    };
  }
}
