package eu.dnetlib.functionality.modular.ui;

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

import javax.servlet.http.HttpServletResponse;

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

@Controller
public class ModularUIStaticFilesController {
	
	private static final String  RESOURCE_PATH = "/eu/dnetlib/functionality/modular/ui/resources/";
	private static final Log log = LogFactory.getLog(ModularUIStaticFilesController.class); // NOPMD by marko on 11/24/08 5:02 PM
	private final static Map<String, String> extToMime = new HashMap<String, String>();
	static {
		extToMime.put("js", "text/javascript");
		extToMime.put("css", "text/css");
		extToMime.put("png", "image/png");
		extToMime.put("jpg", "image/jpeg");
		extToMime.put("gif", "image/gif");
		extToMime.put("html", "text/html");
	}

	@RequestMapping(value = "/**/file.get")
	public void file(HttpServletResponse response, @RequestParam(value = "src", required = true) final String src) throws Exception {
		if (renderStatic(response, src)) {
			log.debug("Static file " + src);
		} else {
			log.warn("Static file " + src + " NOT FOUND");
		}
	}

	protected boolean renderStatic(final HttpServletResponse response, final String name) throws IOException {
		String ext = name.substring(name.lastIndexOf('.') + 1, name.length());
		String dir = "";
		if      (ext.equalsIgnoreCase("js"))   dir += "js/";
		else if (ext.equalsIgnoreCase("css"))  dir += "css/";
		else if (ext.equalsIgnoreCase("html")) dir += "html/";
		else                                   dir += "img/";
		return renderStatic(response, getClass().getResourceAsStream(RESOURCE_PATH + dir + name), extToMime.get(ext));
	}

	protected boolean renderStatic(final HttpServletResponse response, final InputStream input, final String contentType) throws IOException {
		if (input != null) {
			response.setContentType(contentType);
			IOUtils.copy(input, response.getOutputStream());
			return true;
		}
		return false;
	}       

	protected boolean renderStatic(final HttpServletResponse response, final Reader input, final String contentType) throws IOException {
		if (input != null) {
			response.setContentType(contentType);
			IOUtils.copy(input, response.getOutputStream());
			return true;
		}
		return false;
	}
}
