package de.ivu.elect.business.system.control;

import java.io.File;
import java.io.Serializable;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.business.ElectSystemProperties;
import de.ivu.elect.business.konfiguration.entity.KonfigurationLoader;


import static de.ivu.elect.business.konfiguration.entity.ElectKonfigurationWerte.ELECT_COMMON_TEMP_VERZEICHNIS_PFAD;

/**
 * on 11.11.2016.
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class TempDir implements Serializable {

  private static final Logger LOG = LoggerFactory.getLogger(TempDir.class);

  private static final long serialVersionUID = 1L;

  @Inject
  private transient KonfigurationLoader konfigurationLoader;

  public File getTempDir() {
    String propertyTmpDir = System.getProperty(ElectSystemProperties.TEMP_DIR_SYSTEM_PROPERTY_KEY);

    String pathname = konfigurationLoader.resolveStringValue(ELECT_COMMON_TEMP_VERZEICHNIS_PFAD);

    if (StringUtils.isNotBlank(propertyTmpDir)) {
      File result = new File(propertyTmpDir);
      if (!result.isDirectory()) {
        try {
          //noinspection ResultOfMethodCallIgnored
          result.mkdirs();
        } catch (Exception e) {
          // ignorieren
        }
      }
      if (result.isDirectory()) {
        if (StringUtils.isNotBlank(pathname) && !propertyTmpDir.equals(pathname)) {
          LOG.info("Setze tmp-dir Konfiguration auf Wert aus Property: " + propertyTmpDir);
          konfigurationLoader.setValue(ELECT_COMMON_TEMP_VERZEICHNIS_PFAD, propertyTmpDir); // ELECT-14942
        }
        return result;
      }
    }

    if (StringUtils.isBlank(pathname) || !new File(pathname).isDirectory()) {
      String property = System.getProperty("java.io.tmpdir");
      LOG.warn("Temp nicht konfiguriert oder kein Verzeichnis: '" + pathname + "' - fallback: '" + property + "'");
      return new File(property);
    }
    return new File(pathname);
  }
}
