/*
 * $Header: /home/cvspublic/jakarta-slide/projector/src/java/org/apache/slide/projector/processor/tree/TreeLocalizer.java,v 1.8 2004/12/29 17:25:38 dflorey Exp $
 * $Revision: 1.8 $
 * $Date: 2004/12/29 17:25:38 $
 *
 * ====================================================================
 *
 * Copyright 2004 The Apache Software Foundation 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.slide.projector.processor.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.contract.Context;
import org.apache.commons.contract.EnvironmentConsumer;
import org.apache.commons.contract.Processor;
import org.apache.commons.contract.Result;
import org.apache.commons.contract.constraints.ArrayConstraints;
import org.apache.commons.contract.constraints.LocaleConstraints;
import org.apache.commons.contract.constraints.StringConstraints;
import org.apache.commons.contract.constraints.TreeConstraints;
import org.apache.commons.contract.descriptor.ParameterDescriptor;
import org.apache.commons.contract.descriptor.RequiredEnvironmentDescriptor;
import org.apache.commons.contract.descriptor.ResultDescriptor;
import org.apache.commons.contract.descriptor.ResultEntryDescriptor;
import org.apache.commons.contract.descriptor.StateDescriptor;
import org.apache.commons.contract.i18n.ParameterMessage;
import org.apache.commons.i18n.LocalizedMessage;
import org.apache.commons.i18n.MessageManager;
import org.apache.commons.i18n.MessageNotFoundException;
import org.apache.slide.projector.Projector;
import org.apache.slide.projector.engine.ProcessorManager;
import org.apache.slide.projector.processor.SimpleProcessor;

/**
 * The TreeLocalizer class
 * 
 */
public class TreeLocalizer implements Processor, EnvironmentConsumer  {
    private static Logger logger = Logger.getLogger(TreeLocalizer.class.getName());

    public final static String LOCALE = "locale";
    
    protected final static String IMAGE_IDENTIFIER = "image";

    private final static ParameterDescriptor[] parameterDescriptors = new ParameterDescriptor[] {
        new ParameterDescriptor(SimpleProcessor.INPUT, new ParameterMessage("treeLocalizer/input"), new TreeConstraints(new StringConstraints()))
    };
    
    private final static ResultDescriptor[] resultDescriptors = new ResultDescriptor[] {
            new ResultDescriptor(StateDescriptor.OK_DESCRIPTOR,
            new ResultEntryDescriptor[] {
                new ResultEntryDescriptor(SimpleProcessor.OUTPUT, new LocalizedMessage("treeLocalizer/output"), ArrayConstraints.UNCONSTRAINED)
            })
    };

    private final static RequiredEnvironmentDescriptor[] requiredEnvironmentDescriptors = new RequiredEnvironmentDescriptor[] {
    		new RequiredEnvironmentDescriptor(LOCALE, Projector.SESSION_STORE, new ParameterMessage("treeLocalized/requiredEnvironment/locale"), new LocaleConstraints(), Locale.getDefault())
    };

    public Result process(Map parameter, Context context) throws Exception {
        Object []resources = (Object [])parameter.get(SimpleProcessor.INPUT);
        Locale locale = (Locale)context.getStore(Projector.SESSION_STORE).get(LOCALE, context);
        return new Result(StateDescriptor.OK, SimpleProcessor.OUTPUT, localize(resources, locale, context));
    }

    private Object[] localize(Object []resources, Locale locale, Context context) throws Exception {
        List localizedResources = new ArrayList();
        for ( int i = 0; i < resources.length; i++ ) {
            if ( resources[i] instanceof String ) {
                Map localizedMap = new HashMap();
                try {
                	localizedMap.put(TreeRenderer.ID, ProcessorManager.getInstance().process(ProcessorManager.URL, resources[i], context));
                	Map entries = MessageManager.getEntries((String)resources[i], locale);
                    for ( Iterator j = entries.entrySet().iterator(); j.hasNext(); ) {
                        Map.Entry entry = (Map.Entry)j.next();
                        String key = (String)entry.getKey();
                        String value = (String)entry.getValue();
                        if ( key.startsWith(IMAGE_IDENTIFIER) ) {
                        	key = key.substring(IMAGE_IDENTIFIER.length()+1);
                            localizedMap.put(key, ProcessorManager.getInstance().process(ProcessorManager.BINARY, value, "url", context));
                        } else {
                            localizedMap.put(key, value);
                        }
                    }
                } catch ( MessageNotFoundException exception ) {
                    logger.log(Level.SEVERE, "No message found while localizing tree", exception);
                }
                localizedResources.add(localizedMap);
            } else if ( resources[i] instanceof Object[] ) {
                localizedResources.add(localize((Object[])resources[i], locale, context));
            }
        }
        return localizedResources.toArray();
    }

    public ParameterDescriptor[] getParameterDescriptors() {
        return parameterDescriptors;
    }

    public ResultDescriptor[] getResultDescriptors() {
        return resultDescriptors;
    }

    public RequiredEnvironmentDescriptor[] getRequiredEnvironmentDescriptors() {
		return requiredEnvironmentDescriptors;
	}
}
