/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.sitemesh;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.module.sitemesh.Factory;
import com.opensymphony.module.sitemesh.HTMLPage;
import com.opensymphony.module.sitemesh.Page;
import com.opensymphony.module.sitemesh.PageParser;
import com.opensymphony.module.sitemesh.filter.HttpContentType;
import com.opensymphony.sitemesh.Content;
import com.opensymphony.sitemesh.ContentProcessor;
import com.opensymphony.sitemesh.SiteMeshContext;
import com.opensymphony.sitemesh.compatability.HTMLPage2Content;
import com.opensymphony.sitemesh.webapp.SiteMeshWebAppContext;

/**
 */
public class HTMLPageContentProcessor implements ContentProcessor {
	private final Factory factory;

	/**
	 * Constructor
	 *
	 * @param factory factory
	 */
	public HTMLPageContentProcessor(Factory factory) {
		this.factory = factory;
	}

	/**
	 * handles
	 *
	 * @param contentType contentType
	 * @return true if the contentType should be parse
	 */
	public boolean handles(String contentType) {
		return factory.shouldParsePage(contentType);
	}

	/**
	 * handles
	 *
	 * @param context context
	 * @return true if the context does not excluded
	 */
	public boolean handles(SiteMeshContext context) {
		SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext)context;
		return !factory.isPathExcluded(extractRequestPath(webAppContext.getRequest()));
	}

	private String extractRequestPath(HttpServletRequest request) {
		String servletPath = request.getServletPath();
		String pathInfo = request.getPathInfo();
		return (servletPath == null ? "" : servletPath) + (pathInfo == null ? "" : pathInfo);
	}

	/**
	 * build
	 *
	 * @param data data
	 * @param context context
	 * @return content
	 * @throws IOException if an io exception occurs
	 */
	public Content build(char[] data, SiteMeshContext context) throws IOException {
		HttpContentType httpContentType = new HttpContentType(context.getContentType());
		PageParser pageParser = factory.getPageParser(httpContentType.getType());
		Page page = pageParser.parse(data);
		return new HTMLPage2Content((HTMLPage)page);
	}
}
