
package de.ivu.elect.presentation.dokumente.action;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;

import de.ivu.elect.business.dokumente.entity.DokumentVorlage;
import de.ivu.elect.business.dokumente.entity.DokumentVorlageArt;
import de.ivu.elect.business.exchange.control.ImportExportStreamCreator;
import de.ivu.elect.business.security.UseCasePermission;
import de.ivu.elect.jee.faces.download.DownloadAction;

public class DokumentVorlageDownloadAction extends AbstractDokumentVorlageAction {

  private static final long serialVersionUID = 1L;

  private static final Set<String> FILTERPREFIX = new HashSet<>(List.of(DokumentVorlageArt.LEERFORMULAR_PREFIX + "-"));

  @Inject
  private transient ImportExportStreamCreator streamCreator;

  @Inject
  private transient DownloadAction downloadAction;

  public DokumentVorlageDownloadAction() {
    super();
  }

  @Override
  protected UseCasePermission getRequiredPermission() {
    return UseCasePermission.DOKUMENT_VORLAGE_SEARCH;
  }

  @Override
  protected String doIt(DokumentVorlage entity) {
    DefaultStreamedContent defaultStreamedContent = entity.getDatei().getDefaultStreamedContent(streamCreator);

    // ELECT-14592
    defaultStreamedContent = filterDateiname(defaultStreamedContent);

    download(defaultStreamedContent);

    return null;
  }

  private DefaultStreamedContent filterDateiname(DefaultStreamedContent defaultStreamedContent) {
    if (isFilterDateinameNotwendig(defaultStreamedContent)) {

      return DefaultStreamedContent.builder().stream(defaultStreamedContent::getStream).contentType(defaultStreamedContent.getContentType())
          .contentEncoding(defaultStreamedContent.getContentEncoding()).name(filterDateiname(defaultStreamedContent.getName())).contentLength(defaultStreamedContent.getContentLength()).build();
    }
    return defaultStreamedContent;

  }

  private String filterDateiname(String name) {
    var nameLower = name.toLowerCase();
    return FILTERPREFIX.stream().filter(nameLower::startsWith).findFirst().map(filterprefix -> name.substring(filterprefix.length())).orElse(name);

  }

  private boolean isFilterDateinameNotwendig(DefaultStreamedContent defaultStreamedContent) {
    if (StringUtils.isBlank(defaultStreamedContent.getName())) {
      return false;
    }
    var dateiName = defaultStreamedContent.getName().toLowerCase();
    return FILTERPREFIX.stream().anyMatch(dateiName::startsWith);

  }

  private void download(DefaultStreamedContent content) {
    downloadAction.download(content);
  }

  @Override
  protected boolean isAsyncSupported() {
    return false;
  }

  @Override
  public String getLabelKey() {
    return "datei.import.action.download";
  }

  @Override
  public String getIcon() {
    return appIcons.getIconDownload();
  }
}
