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

import java.io.File;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Nullable;
import javax.ejb.Stateless;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

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

@Stateless
public class WesTemplateFinder implements Serializable {
  private static final long serialVersionUID = 1L;

  @Inject
  private transient KonfigurationLoader konfigurationLoader;

  public List<String> getTemplateFiles() {
    String path = konfigurationLoader.resolveStringValue(ElectKonfigurationWerte.WES_TEMPLATE_ABLAGEPFAD);
    if (StringUtils.isNotBlank(path)) {
      File dir = new File(path);
      if (dir.isDirectory()) {
        File[] files = dir.listFiles();
        if (files != null) {
          return Arrays.stream(files).filter(File::isFile).map(File::getName).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }
      }
    }

    return Collections.emptyList();
  }

  @Nullable
  public File getTemplateVorlage(String filename) {
    if (StringUtils.isNotBlank(filename)) {
      String path = konfigurationLoader.resolveStringValue(ElectKonfigurationWerte.WES_TEMPLATE_ABLAGEPFAD);
      if (StringUtils.isNotBlank(path)) {
        File dir = new File(path);
        if (dir.isDirectory()) {
          File[] files = dir.listFiles();
          if (files != null) {
            return Arrays.stream(files).filter(file -> filename.equalsIgnoreCase(file.getName())).findFirst().orElse(null);
          }
        }
      }
    }
    return null;
  }
}
