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

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.annotation.Nonnull;

import de.ivu.elect.business.datei.entity.FileType;
import de.ivu.elect.business.exchange.control.FileFormat;
import de.ivu.elect.business.exchange.control.FileKonfiguration;
import de.ivu.elect.business.exchange.control.MappingException;
import de.ivu.elect.business.wahl.control.WahlImportObject;
import de.ivu.elect.business.wahl.entity.WahlImportContext;
import de.ivu.elect.jee.exchange.Violations;

public abstract class AbstractWahlXmlZipImportMapper extends AbstractWahlXMLImportMapper {

  public AbstractWahlXmlZipImportMapper() {
    super();
  }

  @Override
  public FileFormat getFileFormat() {
    FileFormat fileFormatArchived = super.getFileFormat();

    return new FileFormat(fileFormatArchived.getName(), FileType.ZIP, fileFormatArchived.getFileType());
  }

  @Override
  public Violations validateInputFormat(InputStream is, WahlImportContext noContext, FileKonfiguration fileKonfiguration) {
    try {
      ZipInputStream zis = getZipInputStream(is);

      // erwartet wird genau ein Entry...
      ZipEntry entry = zis.getNextEntry();
      if (entry == null) {
        return new Violations();
      }

      return super.validateInputFormat(zis, noContext, fileKonfiguration);
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  @Override
  public WahlImportObject deserialize(InputStream is, WahlImportContext noContext, FileKonfiguration fileKonfiguration) throws MappingException {
    try(ZipInputStream zis = getZipInputStream(is)) {

      // erwartet wird genau ein Entry...
      ZipEntry entry = zis.getNextEntry();
      if (entry == null) {
        return null;
      }
      return super.deserialize(zis, noContext, fileKonfiguration);

    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  @Nonnull
  protected ZipInputStream getZipInputStream(final InputStream is) {
    return new NonClosableZipInputStream(is);
  }

  private static class NonClosableZipInputStream extends ZipInputStream {

    public NonClosableZipInputStream(InputStream is) {
      super(is);
    }

    @Override
    public void close() throws IOException {
      // do nothing
    }
  }
}
