package eu.dnetlib.enabling.inspector;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DefaultStaticFilesController {

	private final Map<String, String> extToMime = new HashMap<String, String>();

	public DefaultStaticFilesController() {
		extToMime.put("js", "text/javascript");
		extToMime.put("css", "text/css");
		extToMime.put("png", "image/png");
		extToMime.put("jpg", "image/jpeg");
	}

	@RequestMapping(value = "/inspector/static.do")
	public void stat(ServletResponse response, OutputStream out, @RequestParam(value = "src", required = true) final String src) throws Exception {
		renderStatic(response, out, src);
	}

	protected void renderStatic(final ServletResponse response, final OutputStream output, final String name) throws IOException {
		String ext = name.substring(name.lastIndexOf('.') + 1, name.length());

		renderStatic(response, output, getClass().getResourceAsStream("/eu/dnetlib/enabling/views/inspector/" + name), extToMime.get(ext));
	}

	protected void renderStatic(final ServletResponse response, final OutputStream output, final InputStream input, final String contentType)
			throws IOException {
		response.setContentType(contentType);
		IOUtils.copy(input, output);
	}
}
