/*
 * 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.struts2.sitemesh;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.views.freemarker.FreemarkerManager;

import com.opensymphony.module.sitemesh.DecoratorMapper;
import com.opensymphony.sitemesh.Content;
import com.opensymphony.sitemesh.DecoratorSelector;
import com.opensymphony.sitemesh.SiteMeshContext;
import com.opensymphony.sitemesh.compatability.Content2HTMLPage;
import com.opensymphony.sitemesh.webapp.SiteMeshWebAppContext;
import com.opensymphony.sitemesh.webapp.decorator.NoDecorator;

/**
 */
public class FreemarkerDecoratorSelector implements DecoratorSelector {
	private final DecoratorMapper decoratorMapper;
	private final FreemarkerManager freemarkerManager;

	/**
	 * @param decoratorMapper decoratorMapper
	 */
	public FreemarkerDecoratorSelector(FreemarkerManager freemarkerManager, DecoratorMapper decoratorMapper) {
		this.freemarkerManager = freemarkerManager;
		this.decoratorMapper = decoratorMapper;
	}

	/**
	 * @see com.opensymphony.sitemesh.DecoratorSelector#selectDecorator(com.opensymphony.sitemesh.Content,
	 *      com.opensymphony.sitemesh.SiteMeshContext)
	 */
	public com.opensymphony.sitemesh.Decorator selectDecorator(Content content,
			SiteMeshContext context) {

		SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext)context;
		HttpServletRequest request = webAppContext.getRequest();
		com.opensymphony.module.sitemesh.Decorator decorator = decoratorMapper.getDecorator(
			request, new Content2HTMLPage(content, request));
		if (decorator == null || decorator.getPage() == null) {
			return new NoDecorator();
		}
		else {
			return new FreemarkerDecorator(freemarkerManager, webAppContext.getServletContext(), decorator);
		}
	}

}
