/*
 * $Id: CssFilterServlet.java,v 1.2 2006/10/04 03:15:14 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: CssFilterServlet.java,v $
 * Revision 1.2  2006/10/04 03:15:14  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.1  2005/02/15 15:16:10  bigmac
 * *** empty log message ***
 *
 */
package vkc.servlets;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vkc.db.entities.VKCUser;
import vkc.util.FileUtils;
import vkc.util.ServletUtils;
import vkc.util.StringUtils;
import vkc.view.WebShare;

/**
 * Servlet zum Ausliefern von CSS-Dateien für VKC. Referenzen auf z.B.
 * Bilder-URLs werden dabei an die Webapplikation angepasst.
 * <p>
 * 
 * @author bigmac
 */
public class CssFilterServlet extends HttpServlet {

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String uri = StringUtils.normalize(request.getRequestURI());
		// Context-Path muss raus aus der URL
		uri = uri.substring(request.getContextPath().length());

		String uriRealPath = getServletContext().getRealPath(uri);
		
		if (uriRealPath == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			
			return;
		}
		
		File cssFile = new File(uriRealPath);
		
		if (!cssFile.exists()) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			
			return;
		}
		
		VKCUser user = ServletUtils.getUser(request);
		String content = FileUtils.getFileAsString(cssFile);
		content = StringUtils.replaceToken(content, "${application.rooturl}",
				WebShare.getRootURL() + request.getContextPath());
		content = StringUtils.replaceToken(content, "${template.name}",
				user != null ? user.getTemplate().getName() : WebShare.DEFAULT_TEMPLATE);

		response.setContentType("text/css");
		response.getWriter().print(content);
		response.getWriter().close();
	}
}
