
package de.ivu.elect.business.datei.entity;

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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import de.ivu.elect.business.exchange.control.FileFormat;
import de.ivu.elect.jee.faces.Messages;
import de.ivu.elect.util.FileUtil;

public abstract class AbstractDateiFileNames implements DateiFileNames {

  protected static final char DELIMITER = '-';

  protected static final String DATE_PATTERN_EXTERN = "yyyyMMdd-HHmmss";

  protected static final String DATE_PATTERN_INTERN = "yyyyMMdd_HHmmssSSS";

  private static final AtomicLong COUNTER = new AtomicLong(System.currentTimeMillis());

  private final Messages messages;

  public AbstractDateiFileNames(Messages messages) {
    super();

    this.messages = messages;
  }

  protected boolean existsMessageKey(String msgKey) {
    return isNotBlank(msgKey) && getMessages().isMessageKeyVorhanden(msgKey);
  }

  protected String getMessage(Enum< ? > enumValue, Object... params) {
    return getMessages().lokalisiere(enumValue, params);
  }

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

  protected Messages getMessages() {
    return messages;
  }

  protected String getCurrentDateFormatted(String pattern) {
    return new SimpleDateFormat(pattern).format(new Date());
  }

  protected String generateDateiname(FileFormat fileFormat, String fileNamePrefix, boolean uniqueSuffixAdded) {
    String simpleFileName = "";

    if (isNotBlank(fileNamePrefix)) {
      simpleFileName += fileNamePrefix;
    }

    if (uniqueSuffixAdded) {
      if (simpleFileName.length() > 0) {
        simpleFileName += DELIMITER;
      }

      simpleFileName += generateUniqueFileNamePart();
    }

    return normalize(simpleFileName, false, fileFormat.getFileType());// ELECT-8553 "normalisieren"
  }

  protected String generateUniqueFileNamePart() {
    return getCurrentDateFormatted(DATE_PATTERN_INTERN) + DELIMITER + COUNTER.addAndGet(1L);
  }

  protected String normalize(CharSequence simpleFileName, boolean preserveCase, FileType fileType) {
    return FileUtil.normalizeFileName(simpleFileName.toString(), preserveCase) + "." + fileType.getFileExtension();
  }
}
