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

import de.ivu.elect.business.datei.entity.DateiImportBerichtCustomData;
import de.ivu.elect.business.exchange.entity.DateiImportArt;
import de.ivu.elect.business.mandant.entity.Mandant;
import de.ivu.elect.business.wahl.entity.WahlOderWahltermin;
import de.ivu.elect.jee.exchange.ImportOptions;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDatenCreator extends AbstractDatenCreator {
  private static final Logger LOG = LoggerFactory.getLogger(InputStreamDatenCreator.class);


  public <ImportObject, Context, CustomDateiImportBerichtCustomData extends DateiImportBerichtCustomData> void importiere(
          AbstractImporter<ImportObject, Context, CustomDateiImportBerichtCustomData> importer, InputStream is, FileFormat fileFormat,
          DateiImportArt dateiImportArt, Mandant mandant, WahlOderWahltermin wahlOderWahltermin, Context context, ImportOptions importOptions) throws IOException {


    File targetFile = File.createTempFile("inputfile" + System.currentTimeMillis(), "inputfile" + Math.random());

    try {
      FileUtils.copyInputStreamToFile(is, targetFile);
      super.importiere(importer, targetFile.getAbsolutePath(), fileFormat, dateiImportArt, mandant, wahlOderWahltermin, context, importOptions, ignore -> {
      }, new DateiImportBerichtCustomData());
    } finally {
      FileUtils.deleteQuietly(targetFile);
    }
  }

  @Override
  protected InputStream getInputStream(String filePath) throws IOException {
    return new FileInputStream(filePath);
  }

  @Override
  public Logger getLog() {
    return LOG;
  }
}
