package org.exist.cocoon;

import java.util.HashMap;
import java.util.Map;

import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.acting.ServiceableAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;

/**
 * Cocoon action to extract parts of a request parameter,
 * used by risten.no.
 * The input string is of type: /db/ordbase/TYPE/COLL
 * The input string is found in a request parameter named 'srchcoll'
 * The action returns the TYPE and COLL parts in the sitemap parameters
 * requestType and requestCollection
 * 
 * @author sjur
 */
public class RistennoRequestAction extends ServiceableAction implements ThreadSafe {

    public final static String MAP_TYPE = "requestType";
    public final static String MAP_COLL = "requestCollection";

	/* (non-Javadoc)
	 * @see org.apache.cocoon.acting.Action#act(
	             org.apache.cocoon.environment.Redirector,
	             org.apache.cocoon.environment.SourceResolver,
	             java.util.Map,
	             java.lang.String,
	             org.apache.avalon.framework.parameters.Parameters)
	 */
	public Map act(
		Redirector redirector,
		SourceResolver resolver,
		Map objectModel,
		String source,
		Parameters parameters)
		throws Exception {

		Map map = new HashMap();
		Request request = ObjectModelHelper.getRequest( objectModel );

        String query = request.getQueryString();
//		if ( query == null ) {
//			getLogger().error( "Risten.no-action: No query!" );
//			return null;
//		}

        String collpath;
        try {
		      collpath = request.getParameter("srchcoll");
		      boolean bool = collpath.contains("/");
		}
		catch (NullPointerException e) {
		      getLogger().error( "Risten.no-action: no 'srchcoll' parameter!" );
		      return null;
        }
//        String collpath = request.getParameter("srchcoll"); it should be ok 
//like this - will the if () construct put the content into the variable if it
// isn't null? - yes - ok
// The following comment is used for DEBUGing - just uncomment
//		getLogger().error(collpath);
        if (!collpath.contains("/")) {
            getLogger().error( "Risten.no-action: no collection path! " + 
                                collpath );
            return null;
        }
		String[] result = collpath.split("/"); //what if there is no '/' ?

		String type = result[3];
		String coll = result[4];
// The following comments are used for DEBUGing - just uncomment
//		getLogger().error( "Risten.no-action: type = " + type);
//		getLogger().error( "Risten.no-action: coll = " + coll);

        map.put(MAP_TYPE, type );
        map.put(MAP_COLL, coll );

        return map;
	}
}
