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

import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.lowerCase;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

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

import javax.inject.Inject;

import de.ivu.elect.jee.faces.Messages;
import de.ivu.elect.jee.faces.UserLocale;

public abstract class AbstractMaschinenlesbarerBereichMapper implements MaschinenlesbarerBereichMapper {

  private static final long serialVersionUID = 1L;

  protected static final String FORMAT_VALUE_UNDEFINED = "";

  protected static final int FORMAT_VALUE_UNDEFINED_KEY_CODE = Integer.MAX_VALUE;

  @Inject
  private transient Messages messages;

  @Inject
  private transient UserLocale userLocale;

  public AbstractMaschinenlesbarerBereichMapper() {
    super();
  }

  protected AbstractMaschinenlesbarerBereichMapper(Messages messages, UserLocale userLocale) {
    super();

    this.messages = messages;
    this.userLocale = userLocale;
  }

  protected String getMessage(String msgKey, Object... params) {
    return getMessages().getMessageForMessageKey(msgKey, params);
  }

  protected Messages getMessages() {
    return messages;
  }

  @Override
  public int getFormatSeparatorKeyCode() {
    return getKeyCodeOrDefault(getFormatSeparator());
  }

  @Override
  public int getFormatPrefixKeyCode() {
    return getKeyCodeOrDefault(getFormatPrefix());
  }

  @Override
  public int getFormatSuffixKeyCode() {
    return getKeyCodeOrDefault(getFormatSuffix());
  }

  protected String[] extractFormatValues(String value) {
    return extractFormatValues(value, getFormatSeparator());
  }

  protected String[] extractFormatValues(String value, String separator) {
    if (isNotBlank(value)) {
      return value.split(separator, -1);
    }

    return new String[0];
  }

  protected String convertToStringCapitalized(String value) {
    return capitalize(lowerCase(fixBlankToEmpty(value), userLocale.getLocale()));
  }

  protected Date convertToDate(String value, String pattern) {
    try {
      return new SimpleDateFormat(pattern).parse(value);
    } catch (ParseException ignored) {
    }

    return null;
  }

  protected String fixBlankToEmpty(String value) {
    return trimToEmpty(value);
  }

  private int getKeyCodeOrDefault(String value) {
    if (value != null && value.length() == 1) {
      if (value.length() == 1) {
        return value.charAt(0);
      }
    }

    return FORMAT_VALUE_UNDEFINED_KEY_CODE;
  }
}
