/* ====================================================================
 * 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/>.
 */

package org.apache.jetspeed.services.persistence;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// Jetspeed classes
import org.apache.jetspeed.om.profile.Entry;
import org.apache.jetspeed.om.profile.PSMLDocument;
import org.apache.jetspeed.om.profile.Portlets;
import org.apache.jetspeed.om.profile.Profile;
import org.apache.jetspeed.portal.JetspeedPortletInstance;
import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.portal.PortletException;
import org.apache.jetspeed.portal.PortletInstance;
import org.apache.jetspeed.services.PortletFactory;
import org.apache.jetspeed.services.PsmlManager;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.rundata.JetspeedRunData;

// Turbine classes
import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.util.RunData;

/**
 * Implementation of the Portal Persistence Service for storing and
 * retrieving portlet instances.
 *
 * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
 * @version $Id: JetspeedPortalPersistenceService.java,v 1.4 2003/07/23 19:50:21 morciuch Exp $
 */
public class JetspeedPortalPersistenceService
    extends TurbineBaseService
    implements PortalPersistenceService
{    
    /**
     * Static initialization of the logger for this class
     */    
    private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(JetspeedPortalPersistenceService.class.getName());    
    
    /**
     * Use this to verify the RunData object in use is going to be the Jetspeed
     * RunData object.  This way we know right off, whether or not things are going
     * to work.
     * 
     */
    public void init(RunData data) throws InitializationException
    {
        if (!(data instanceof JetspeedRunData))
        {
            logger.error(
                "[PortalPersistenceService] The current RunData implenetation does not implement the JetspeedRunData interface.");
            setInit(false);
            throw new InitializationException("The current RunData implenetation does not implement the JetspeedRunData interface.");
        }

        super.init(data);
    }    
    
    /**
     * @see PortalPersistenceService#getInstance(Portlet, Profile)
     */
    public PortletInstance getInstance(Portlet portlet, Profile profile)
    {
        return new JetspeedPortletInstance(portlet, profile);
    }

    /**
     * @see PortalPersistenceService#getInstance(Portlet, RunData)
     */
    public PortletInstance getInstance(Portlet portlet, RunData data)
    {
     	String attrKey = "portlet_instance:"+portlet.getID();
    	// optimize portlet instance retreival by saving it to the request
    	// this also guarantees the PortletInstance object is the same
    	// object for the entire life of the request
    	PortletInstance instance = (PortletInstance) data.getRequest().getAttribute(attrKey);
    	if(instance != null)
    	{
    		return instance;
    	}
    	else
    	{
         	instance=  new JetspeedPortletInstance(portlet, data);
         	data.getRequest().setAttribute(attrKey, instance);
         	return instance;
    	}

    }

    /**
     * @see PortalPersistenceService#store(PortletInstance)
     */
    public void store(PortletInstance pPortlet) throws PortalPersistenceException
    {
        Profile profile = pPortlet.getProfile();
        profile.setDocument(pPortlet.getDocument());
        
        if(!PsmlManager.store(profile))
        {
            throw new PortalPersistenceException("Unable to write portlet information.");
        }
    }

    /**
     * @see PortalPersistenceService#getInstances(Portlet, Profile)
     */
    public List getInstances( Profile profile) throws PortletException
    {
        PSMLDocument doc = profile.getDocument();
        Portlets portlets =  doc.getPortlets();
        ArrayList pList = new ArrayList();
       
       buildAllEntries(portlets, pList, profile);
        
        return pList;
    }

    /**
     * @see PortalPersistenceService#getInstances(Portlet, RunData)
     */
    public List getInstances( RunData data) throws PortletException
    {
        JetspeedRunData jData = (JetspeedRunData) data;
        return getInstances(jData.getProfile());
    }
    
    protected void buildAllEntries(Portlets portlets, ArrayList entries, Profile profile) throws PortletException
    {
        // First let's add all the Entries in the current level
        Iterator eItr = portlets.getEntriesIterator();
        while(eItr.hasNext())
        {
            Object obj =  eItr.next();
            Entry entry = (Entry)obj;
            Portlet portlet = PortletFactory.getPortlet(entry);
            entries.add(new JetspeedPortletInstance(portlet, profile));
        }
        
        //Now if there are child levels, drill down recursively
        if(portlets.getPortletsCount() > 0)
        {
            Iterator pItr = portlets.getPortletsIterator();
            while(pItr.hasNext())
            {
                Portlets childPortlets = (Portlets)pItr.next();
                buildAllEntries(childPortlets, entries, profile);
            }
            
            return;
        }
        else
        // bootstrap
        {
            return;
        }
        
        
    }

}