
package de.ivu.elect.presentation.hilfe;

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

import javax.annotation.Nullable;

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

import de.ivu.elect.business.datei.entity.BinaryUnit;

public class HelpReader implements Serializable {

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

  private static final int BUFFER_SIZE_IN_BYTES = BinaryUnit.bytesOf(8, BinaryUnit.KIBIBYTE);

  public static final String HELP_PACKAGE = "/help.zip";

  private static final long serialVersionUID = 1L;

  public boolean isHilfeVorhanden() {
    try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(HELP_PACKAGE)) {
      return is != null;
    } catch (Exception e) {
      return false;
    }
  }

  @Nullable
  public byte[] readContentFromHelp(String name) {
    try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(HELP_PACKAGE)) {
      if (is == null) {
        return null;
      }
      try (ZipInputStream zis = new ZipInputStream(is)) {
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
          if (isContentFound(name, zipEntry)) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE_IN_BYTES);
            IOUtils.copy(zis, bos);
            return bos.toByteArray();
          }
        }
      }
    } catch (IOException e) {
      LOG.warn("Hilfe nicht gefunden: " + name + ", " + e.getMessage());
    }
    return null;
  }

  protected boolean isContentFound(String name, ZipEntry zipEntry) {
    return name.equals(zipEntry.getName());
  }
}
