
package de.ivu.elect.business.exchange.boundary;

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.convert.ConverterException;

public class ExchangeDateConverter implements ExchangeTypeConverter {

  /**
   * The default format which is used when no format is explicitly given.
   */
  private static final String DEFAULT_FORMAT = "dd.MM.yyyy";

  private final SimpleDateFormat dateFormat;

  public ExchangeDateConverter() {
    this(DEFAULT_FORMAT);
  }

  public ExchangeDateConverter(String dateFormat) {
    super();

    try {
      this.dateFormat = new SimpleDateFormat(dateFormat);
    } catch (Exception ex) {
      throw new ConverterException("Could not create a " + this.getClass().getName() + "  with format " + dateFormat, ex);
    }
  }

  /**
   * copied from org.jsefa.common.converter modified by WAA
   */
  @Override
  public synchronized String toString(Object value) {
    if (value == null) {
      return null;
    }

    return this.dateFormat.format((Date) value);
  }

  /**
   * copied from org.jsefa.common.converter modified by WAA
   */
  @Override
  public synchronized Date fromString(String value) {
    if (isBlank(value)) {
      return null;
    }

    try {
      return this.dateFormat.parse(value);
    } catch (ParseException e) {
      throw new ConverterException("Wrong date format: " + value);
    }
  }
}
