/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2003 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/>.
 */

package org.apache.jetspeed.portal.controllers;

//jetspeed support
import org.apache.jetspeed.portal.BasePortletSetConstraints;
import org.apache.jetspeed.portal.PortletConfig;
import org.apache.jetspeed.portal.PortletController;
import org.apache.jetspeed.portal.PortletControllerConfig;
import org.apache.jetspeed.portal.PortletSet;

import org.apache.jetspeed.capability.CapabilityMap;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.om.registry.PortletControllerEntry;
import org.apache.jetspeed.om.registry.MediaTypeEntry;
import org.apache.jetspeed.util.MimeType;

//turbine support
import org.apache.turbine.util.RunData;

//ecs stuff
import org.apache.ecs.ConcreteElement;
import org.apache.ecs.ElementContainer;

import java.util.Map;
import java.util.Iterator;

/**
 @author <a href="mailto:burton@apache.org">Kevin A. Burton</a>
 @version $Id: AbstractPortletController.java,v 1.25 2003/07/23 19:50:16 morciuch Exp $
*/
public abstract class AbstractPortletController implements PortletController
{

    /**
     * Static initialization of the logger for this class
     */    
    private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(AbstractPortletController.class.getName());    
    
    /**
     *  Default padding to be displayed between portlets
     */
    public int DEFAULT_PADDING = 3;

    private String width="100%";
    private PortletSet portlets = null;
    private PortletControllerConfig conf = null;


    /**
    Allows the user to override the default set of portlets...
    */
    public final void setConfig(PortletControllerConfig conf)
    {
        this.conf = conf;
    }


    /**
    */
    public final PortletControllerConfig getConfig()
    {
        return this.conf;
    }

    /**
    Allows the user to override the default set of portlets...
    */
    public final void setPortlets(PortletSet portlets)
    {
      this.portlets = portlets;
    }


    /**
    */
    public final PortletSet getPortlets()
    {
        return this.portlets;
    }

    /**
    */
    public String getWidth() {
        return this.width;
    }

    /**
    */
    public void setWidth(String width) {
        this.width = width;
    }

    /**
    Returns the padding value between the displayed portlets
    */
    public int getPadding() {
        int padding = 0;

        try {
            PortletConfig conf = getPortlets().getPortletConfig();
            padding =  Integer.parseInt( conf.getSkin( "padding" , String.valueOf( DEFAULT_PADDING ) ) );
        } catch ( RuntimeException e ) {
            logger.error("Exception getting padding value", e);
            padding = DEFAULT_PADDING;
        }

        return padding;
    }

    /**
    Sets the padding space to be put between portlets
    */
    public void setPadding(int padding) {
        try {
            PortletConfig conf = getPortlets().getPortletConfig();
            conf.setSkin( "padding" , String.valueOf( padding ) );
        } catch ( RuntimeException e ) {
            logger.error("Exception setting padding value", e);
            // FIXME: What should we do if there's no portlets, config or skin defined ?
        }

    }

    /**
    Sets the padding space to be put between portlets
    */
    public void setPadding(String padding) {
        try {
            PortletConfig conf = getPortlets().getPortletConfig();
            conf.setSkin( "padding" , padding );
        } catch ( RuntimeException e ) {
            logger.error("Exception setting padding value", e);
            // FIXME: What should we do if there's no portlets, config or skin defined ?
        }
    }

    /**
    */
    public void init()
    {
        // no specific init
    }


    /**
    @see Portlet#supportsType
    */
    public boolean supportsType( MimeType mimeType )
    {
        // we now need to check that the control also supports the type...
        PortletControllerEntry entry =
                (PortletControllerEntry)Registry.getEntry(Registry.PORTLET_CONTROLLER,
                                                   getConfig().getName() );
        String baseType = mimeType.toString();

        if (entry!=null)
        {
            Iterator i = entry.listMediaTypes();

            while(i.hasNext())
            {
                String name = (String)i.next();
                MediaTypeEntry media = (MediaTypeEntry)Registry.getEntry(Registry.MEDIA_TYPE, name);

                if (media != null)
                {
                    if (baseType.equals(media.getMimeType()))
                    {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
    */
    public ConcreteElement getContent( RunData rundata )
    {

        CapabilityMap map = ((JetspeedRunData)rundata).getCapability();
        ConcreteElement content = null;

        if ( MimeType.WML.equals( map.getPreferredType() ) )
        {
            content = getWMLContent( portlets, rundata );
        }
        else if ( MimeType.HTML.equals( map.getPreferredType() ) )
        {
            content = getHTMLContent( portlets, rundata );
        }
        else
        {
            // we don't know how to handle this type, maybe a subclass knows
            content = getContent( portlets, rundata );
        }

        return content;
    }

    /**
    */
    protected ConcreteElement getContent( PortletSet set, RunData data )
    {
        return new ElementContainer();
    }

    /**
    */
    protected ConcreteElement getWMLContent( PortletSet set, RunData data )
    {
        return new ElementContainer();
    }

    /**
    */
    protected ConcreteElement getHTMLContent( PortletSet set, RunData data )
    {
        return new ElementContainer();
    }

    /**
     * Creates a constraint object based on an original map source.
     *
     * @param original the source for this constraint object
     * @return a new Constraints object appropriate for this controller
     */
    public PortletSet.Constraints getConstraints( Map original )
    {
        PortletSet.Constraints constraints = new BasePortletSetConstraints();
        if (original != null) constraints.putAll(original);
        return constraints;
    }

}
