/**
 * OW2 Specifications
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: easybeans@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: PersistenceProviderActivator.java 5548 2010-06-22 14:41:54Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.spec.ee.jpa;

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

import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceProviderResolver;
import javax.persistence.spi.PersistenceProviderResolverHolder;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;

/**
 * OSGi activator for
 * @author Florent Benoit
 */
public class PersistenceProviderActivator implements BundleActivator, PersistenceProviderResolver, ServiceListener {

    /**
     * Previous persistence provider that was set in the persistence provider resolver holder.
     */
    private PersistenceProviderResolver previousPersistenceProviderResolver = null;

    /**
     * List of all persistence providers found / registered.
     */
    private List<PersistenceProvider> persistenceProviders = null;

    /**
     * The bundle context.
     */
    private BundleContext bundleContext = null;

    /**
     * Default constructor.
     */
    public PersistenceProviderActivator() {
        this.persistenceProviders = new ArrayList<PersistenceProvider>();
    }

    /**
     * Called when this bundle is started so the Framework can perform the bundle-specific activities necessary to start this
     * bundle. This method can be used to register services or to allocate any resources that this bundle needs.
     * 
     * <p>
     * This method must complete and return to its caller in a timely manner.
     * 
     * @param context The execution context of the bundle being started.
     * @throws Exception If this method throws an exception, this bundle is marked as stopped and the Framework will remove this
     * bundle's listeners, unregister all services registered by this bundle, and release all services used by this bundle.
     */
    public void start(BundleContext context) throws Exception {
        this.bundleContext = context;
        // register as the new persistence provider resolver
        previousPersistenceProviderResolver = PersistenceProviderResolverHolder.getPersistenceProviderResolver();
        PersistenceProviderResolverHolder.setPersistenceProviderResolver(this);

        // Some persistence providers are already here ?
        ServiceReference[] serviceReferences = this.bundleContext.getServiceReferences(PersistenceProvider.class.getName(), null);
        if (serviceReferences != null) {
            for (ServiceReference serviceReference : serviceReferences) {
                PersistenceProvider persistenceProvider = (PersistenceProvider) bundleContext.getService(serviceReference);
                persistenceProviders.add(persistenceProvider);
            }
        }

        // Check to be notified when there are new implementations that are registered
        bundleContext.addServiceListener(this, "(objectClass=" + PersistenceProvider.class.getName() + ")");
    }

    /**
     * Called when this bundle is stopped so the Framework can perform the bundle-specific activities necessary to stop the
     * bundle. In general, this method should undo the work that the <code>BundleActivator.start</code> method started. There
     * should be no active threads that were started by this bundle when this bundle returns. A stopped bundle must not call any
     * Framework objects.
     * 
     * <p>
     * This method must complete and return to its caller in a timely manner.
     * 
     * @param context The execution context of the bundle being stopped.
     * @throws Exception If this method throws an exception, the bundle is still marked as stopped, and the Framework will remove
     * the bundle's listeners, unregister all services registered by the bundle, and release all services used by the bundle.
     */
    public void stop(BundleContext context) throws Exception {
        // unregister
        PersistenceProviderResolverHolder.setPersistenceProviderResolver(previousPersistenceProviderResolver);
    }

    /**
     * Clear cache of providers.
     */
    public void clearCachedProviders() {
        persistenceProviders.clear();
    }

    /**
     * Returns a list of the PersistenceProvider implementations available in the runtime environment.
     * @return list of the persistence providers available in the environment
     */
    public List<PersistenceProvider> getPersistenceProviders() {
        return persistenceProviders;
    }

    /**
     * Checks if there are persistence providers that are being registered/unregistered.
     * @param event The <code>ServiceEvent</code> object.
     */
    public void serviceChanged(ServiceEvent event) {
        ServiceReference serviceRef = event.getServiceReference();
        PersistenceProvider persistenceProvider = (PersistenceProvider) this.bundleContext.getService(serviceRef);

        switch (event.getType()) {
        case ServiceEvent.REGISTERED:
            this.persistenceProviders.add(persistenceProvider);
            break;
        case ServiceEvent.UNREGISTERING:
            this.persistenceProviders.remove(persistenceProvider);
            break;
        default:
            break;
        }
    }
}
