
package de.ivu.elect.jee.faces;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

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

@FacesConverter(forClass = String.class)
public class StringEmptyToNullConverter implements Converter {

  public StringEmptyToNullConverter() {
    super();
  }

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

    // ELECT-7105, der 'NO-BREAK SPACE' == \u00A0 == &#160; kommt bspw. vom NoSelection-Item eines SelectOneMenu und
    // gilt aber NICHT als 'Blank'!
    if (isBlank(result) || "\u00A0".equals(result)) {
      return null;
    }

    return result;
  }

  @Override
  public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (value == null) {
      return null;
    }

    return value.toString();
  }
}
