package de.ivu.elect.nl.eml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.function.Consumer;

import javax.annotation.Nullable;

import org.apache.commons.io.IOUtils;

import de.ivu.elect.jee.exchange.JAXBUtil;
import de.ivu.wahl.wus.oasis.eml.EML;

public class EmlReader {

  static final int BUFFER_SIZE = 1024 * 100;

  public EmlWrapper readEMlNoHash(InputStream is) {
    return readEMl(is, null);
  }

  public EmlWrapper readEMlHash(InputStream is, Consumer<String> hashConsumer) {
    return readEMl(is, hashConsumer);
  }

  private EmlWrapper readEMl(InputStream is, @Nullable Consumer<String> hashConsumer) {
    try {
      if (hashConsumer == null) {
        return new EmlWrapper(new JAXBUtil().unmarshal(EML.class, is));
      } else {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE)) {
          IOUtils.copy(is, bos);

          try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
            hashConsumer.accept(XmlHelper.createHash(bis));
          }

          try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
            return new EmlWrapper(new JAXBUtil().unmarshal(EML.class, bis));
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }
}
