package de.ivu.elect.nl.eml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;

public class ClasspathResourceResolver implements LSResourceResolver {

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


  @Override
  public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
    LOG.info("type = " + type + ", namespaceURI = " + namespaceURI + ", publicId = " + publicId + ", systemId = " + systemId + ", baseURI = " + baseURI);
    try {
      try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(systemId)) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
          IOUtils.copy(stream, bos);
          LSInputImpl input = new LSInputImpl();
          input.setPublicId(publicId);
          input.setSystemId(systemId);
          input.setBaseURI(baseURI);
          input.setCharacterStream(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray())));
          return input;
        }

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

  }
}
