package org.apache.jetspeed.modules.parameters;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Comparator;

import org.apache.jetspeed.om.profile.ProfileLocator;
import org.apache.jetspeed.om.registry.PortletInfoEntry;
import org.apache.jetspeed.om.registry.RegistryEntry;
import org.apache.jetspeed.om.registry.Parameter;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.services.security.PortalResource;
import org.apache.turbine.services.localization.Localization;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

/**
 * Returns list box control populated with registry entries from selected registry.
 * <p>Options:
 * <UL>
 * <LI><code>registry</code> [Portlet|Security|PortletControl|PortletController|Skin|security|MediaType|Client] - registry name</LI> 
 * <LI><code>sort</code> [<strong>true</strong>|false] - return sorted list of items</LI>  
 * <LI><code>select-hidden</code> [<strong>false</strong>|true] - allow multiple selections</LI>  
 * <LI><code>null-if-empty</code> [<strong>true</strong>|false] - do not return a select control if item list is empty</LI>   
 * <LI><code>set-label</code> [<strong>false</strong>|true] - put label in front of the list box based on the registry name</LI>    
 * <LI><code>disabled-if-wml</code> [<strong>false</strong>|true] - set disabled attribute for the list box if using wml</LI>     
 * <LI><code>select-if-simple</code> [<strong>false</strong>|true] - select only entries with parameter "simple" set to true</LI>   
 * </UL> 
 * @author <a href="morciuch@apache.org">Mark Orciuch</a>
 * @version $Id: RegistryEntryListBox.java,v 1.3 2002/11/21 23:49:41 morciuch Exp $  
 */

public class RegistryEntryListBox extends VelocityParameterPresentationStyle
{
    public static final String OPTION_REGISTRY = "registry";
    public static final String OPTION_SORT = "sort";
    public static final String OPTION_SELECT_HIDDEN = "select-hidden";
    public static final String OPTION_NULL_IF_EMPTY = "null-if-empty";
    public static final String OPTION_SET_LABEL = "set-label";
    public static final String OPTION_DISABLED_IF_WML = "disabled-if-wml";
    public static final String OPTION_SELECT_IF_SIMPLE = "select-if-simple";

    /**
     * Put custom objects in the velocity context
     * 
     * @param data
     * @param name
     * @param value
     * @param parms
     * @param context
     */
    public void buildContext(RunData data, String name, String value, Map parms, Context context)
    {
        // Initialize options
        JetspeedRunData jdata = (JetspeedRunData)data;
        String mediaType = jdata.getProfile().getMediaType();
        String regName = (String)getParm(OPTION_REGISTRY, Registry.PORTLET);
        boolean sort = (new Boolean((String)getParm(OPTION_SORT, "true"))).booleanValue();
        boolean selectHidden = (new Boolean((String)getParm(OPTION_SELECT_HIDDEN, "false"))).booleanValue();
        String nullIfEmpty = (String)getParm(OPTION_NULL_IF_EMPTY, "true");
        boolean setLabel = (new Boolean((String)getParm(OPTION_SET_LABEL, "false"))).booleanValue();
        boolean disabledIfWML = (new Boolean((String)getParm(OPTION_DISABLED_IF_WML, "false"))).booleanValue();
        boolean selectIfSimple = (new Boolean((String)getParm(OPTION_SELECT_IF_SIMPLE, "false"))).booleanValue();

        // Iterate thru entries from selected registry
        List list = new ArrayList();
        for (Iterator i = Registry.get(regName).listEntryNames(); i.hasNext();)
        {
            RegistryEntry entry = Registry.getEntry(regName, (String)i.next());
            boolean selected = false;
            selected = JetspeedSecurity.checkPermission((JetspeedUser) data.getUser(), new PortalResource(entry), "customize");
            if (selected && !selectHidden)
            {
                selected = !entry.isHidden();
            }
            if (selected && (entry instanceof PortletInfoEntry))
            {
                selected = ((PortletInfoEntry) entry).hasMediaType(mediaType);
            }
            if (selected && selectIfSimple)
            {
                Parameter simpleParam = ((PortletInfoEntry) entry).getParameter("simple");
                if (simpleParam != null)
                {
                    selected = new Boolean(simpleParam.getValue()).booleanValue();
                }
                else
                {
                    selected = false;
                }
            }
            if (selected)
            {
                list.add(entry);
            }
        }

        // Perform optional sort of list box items
        if (sort)
            Collections.sort(list, 
                             new Comparator()
                             {
                                 public int compare(Object o1, Object o2)
                                 {
                                     String t1 = (((RegistryEntry) o1).getTitle() != null)
                                     ? ((RegistryEntry) o1).getTitle()
                                     : ((RegistryEntry) o1).getName();
                                     String t2 = (((RegistryEntry) o2).getTitle() != null)
                                     ? ((RegistryEntry) o2).getTitle()
                                     : ((RegistryEntry) o2).getName();

                                     return t1.compareTo(t2);
                                 }
                             });

        // Set list box label
        String label = null;
        if (regName.equals(Registry.PORTLET))
        {
            label = Localization.getString("CUSTOMIZER_PORTLET");        
        }
        else if (regName.equals(Registry.SECURITY))
        {
            label = Localization.getString("CUSTOMIZER_SECURITY_REF");
        }
        else if (regName.equals(Registry.MEDIA_TYPE))
        {
            label = Localization.getString("CUSTOMIZER_MEDIATYPE");
        }
        else if (regName.equals(Registry.PORTLET_CONTROLLER))
        {
            label = Localization.getString("CUSTOMIZER_LAYOUT");
        }
        else if (regName.equals(Registry.PORTLET_CONTROL))
        {
            label = Localization.getString("CUSTOMIZER_DECORATION");
        }
        else if (regName.equals(Registry.CLIENT))
        {
            label = "Client";
        }
        else
        {
            label = "";
        }
        context.put("entries", list);
        context.put("nullIfEmpty", nullIfEmpty);
        if (setLabel)
            context.put("label", label);
        if (disabledIfWML && mediaType.equalsIgnoreCase("wml"))
            context.put("disabled", "disabled");
    }

}