
package de.ivu.elect.core.exchange.wahl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.EmlExportMapper;
import de.ivu.elect.business.datei.entity.FileType;
import de.ivu.elect.business.exchange.control.AbstractExchangeContext;
import de.ivu.elect.business.exchange.control.FileFormat;
import de.ivu.elect.business.exchange.control.FileKonfiguration;
import de.ivu.elect.business.wahl.control.AbstractNlExportArtefaktNachSystemExportstatusExportContext;
import de.ivu.elect.business.wahl.entity.Wahl;
import de.ivu.elect.exchange.ExportMapper;

public class NlExportArtefaktNachSystemExportstatusRawExportMapper<C extends AbstractNlExportArtefaktNachSystemExportstatusExportContext, E, D extends AbstractExchangeContext> {

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

  private final Wahl wahl;

  private final ExportMapper<E, D> rawExportMapper;

  public NlExportArtefaktNachSystemExportstatusRawExportMapper(Wahl wahl, ExportMapper<E, D> rawExportMapper) {
    super();

    this.wahl = wahl;

    this.rawExportMapper = rawExportMapper;
  }

  public FileFormat getFileFormat() {
    return rawExportMapper.getFileFormat();
  }

  public void serialize(OutputStream os, C context, E rawEntities, D rawContext, FileKonfiguration fileKonfiguration, boolean closeOutputStream) throws Exception {
    rawContext.putAll(context.getContextParameters()); // ELECT-10450, Parameter zum Signieren mitgeben!

    FileType targetFileType = getFileFormat().getFileType();

    String artefaktTypeName = targetFileType.name();

    if (targetFileType.isXmlFile()) {
      artefaktTypeName = "EML";
    }

    LOG.info("Erzeuge {} [wahl = {}, signierung deaktiviert = {}, fileFormat = {}, fileType = {}]", artefaktTypeName, wahl.getName(),
        Boolean.TRUE.equals(rawContext.get(EmlExportMapper.EML_SIGN_SKIP_KEY, Boolean.class)), getFileFormat().getName(), targetFileType);

    File tempFile = Files.createTempFile("tempFile-" + System.nanoTime(), "." + targetFileType.getFileExtension()).toFile();

    try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(tempFile))) {
      rawExportMapper.serialize(rawEntities, fos, rawContext, fileKonfiguration);
    }

    try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(tempFile))) {
      IOUtils.copy(fis, os);
    }

    try {
      FileUtils.forceDeleteOnExit(tempFile);
    } catch (Exception ex) {
      LOG.warn("FAILED to delete file in the default temporary-file directory [file = {}]", tempFile, ex);
    }
  }
}
