/*
 * Created on Mar 12, 2004
 */
package org.apache.cocoon.generation;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;

/**
 * @author Oscar Picasso
 * @version Mar 12, 2004 - 2:28:03 PM
 */
public class RequestAttributesCacheableVelocityGenerator extends AbstractCacheableVelocityGenerator
{
	private String[] cachingAttributeNames = new String[0];
	private static final String cachingAttributesName = "caching-attributes";

	/**
	 * @see org.apache.cocoon.generation.AbstractCacheableVelocityGenerator#getKey()
	 */
	public Serializable getKey()
	{
		String src = this.inputSource.getURI();
		HashMap key = new HashMap();
		key.put("source", src);
		
		HashMap attributes = new HashMap();
		key.put("attributes", attributes);
		
		Request request = ObjectModelHelper.getRequest(objectModel);
		
		for (int i = 0; i < cachingAttributeNames.length; i++)
		{
			String cachingAttributeName = cachingAttributeNames[i];		
			Object value = request.getAttribute(cachingAttributeName);
			attributes.put(cachingAttributeName, value);
		}

		if (getLogger().isDebugEnabled())
		{
			getLogger().debug("key: " + key);
		}
		return key;
	}

	/**
	 * @see org.apache.avalon.framework.configuration.Configurable#configure(org.apache.avalon.framework.configuration.Configuration)
	 */
	public void configure(Configuration configuration) throws ConfigurationException
	{
		super.configure(configuration);
		String cachingAttributes = configuration.getAttribute(cachingAttributesName, "");
		List keysList = new LinkedList();
		for(StringTokenizer keyElements = new StringTokenizer(cachingAttributes, ", "); keyElements.hasMoreTokens();)
		{
			String keyElement = keyElements.nextToken();
			keysList.add(keyElement);
			if(getLogger().isDebugEnabled())
			{
				getLogger().debug("configuring attribute key: " + keyElement);
			}
		}
		this.cachingAttributeNames = (String[]) keysList.toArray(new String[keysList.size()]);
	}

}
