package com.heckmansoft.surjey.filter;

import java.io.PrintWriter;
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Filter that wraps response in a template.
 *
 * Template should be specified in Web application deployment descriptor
 * (web.xml) under the servlet name "PageTemplate".
 * The response is converted into a string and stored in the request
 * under the attribute "bodyContents".
 * @see javax.servlet.Filter
 */
public class PageTemplateFilter implements Filter
{
    private static final String TMPL_NAME = "PageTemplate";

    private FilterConfig filterConfig;
    private ServletContext context;

    Logger log = Logger.getLogger(PageTemplateFilter.class);

    /**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
        this.filterConfig = filterConfig;
        this.context = filterConfig.getServletContext();
    }

    /**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
        FilterResponseWrapper wrapper;

        // Get the response output stream
        PrintWriter out = response.getWriter();

        // Create a response wrapper for the body
        wrapper = new FilterResponseWrapper((HttpServletResponse) response);

        // Get the body
        chain.doFilter(request,wrapper);

        // Store the body in the request
        request.setAttribute("bodyContents",wrapper.toString());

        RequestDispatcher dispatcher = context.getNamedDispatcher(TMPL_NAME);
        if (dispatcher == null) {
            throw new ServletException("Unable to locate page template: "+TMPL_NAME);
        }

        // Create a response wrapper for the template
        wrapper = new FilterResponseWrapper((HttpServletResponse) response);

        // Include the template page
        dispatcher.include(request, wrapper);

        // Write the response
        out.print(wrapper.toString());

        // Close and flush the response
        out.close();
        response.flushBuffer();
    }

    /**
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
        this.filterConfig = null;
    }

}
