/*
 * 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.views.java;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsException;
import org.apache.struts2.components.template.TemplateRenderingContext;

/**
 * Default implementation of the theme
 */
public class DefaultTheme implements Theme {
	protected static final Log log = LogFactory.getLog(DefaultTheme.class);

	protected String name;

	protected Map<String, TemplateRendererFactory> rendererFactories;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the rendererFactories
	 */
	public Map<String, TemplateRendererFactory> getRendererFactories() {
		return rendererFactories;
	}

	/**
	 * @param rendererFactories the rendererFactories to set
	 */
	public void setRendererFactories(
			Map<String, TemplateRendererFactory> rendererFactories) {
		this.rendererFactories = rendererFactories;
	}

	public void renderTemplate(TemplateRenderingContext context) {
		String templateName = context.getTemplate().getName();
		if (templateName.endsWith(".java")) {
			templateName = templateName.substring(0, templateName.length() - ".java".length());
		}

		TemplateRendererFactory factory = rendererFactories.get(templateName);
		if (factory == null) {
			throw new StrutsException("Unable to find template render factory for "
					+ templateName);
		}

		try {
			if (log.isTraceEnabled()) {
				log.trace("Rendering [" + templateName + "]");
			}
			TemplateRenderer renderer = factory.create(context);
			renderer.render();
		}
		catch (Exception ex) {
			throw new StrutsException("Unable to write: " + templateName, ex);
		}
	}

}
