/**
 * OW2 Specifications
 * Copyright (C) 2010-2012 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: ValidationProviderActivator.java 6220 2012-04-02 08:57:39Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.spec.ee.validation;

import java.net.URL;
import java.util.Map;
import java.util.WeakHashMap;

import javax.validation.ValidationProviderResolver;
import javax.validation.spi.ValidationProvider;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.SynchronousBundleListener;

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

    /**
     * Validation Provider Resolver.
     */
    private ValidationProviderResolverImpl validationProviderResolver;

    /**
     * Previous validation provider that was set in the validation provider resolver holder.
     */
    private ValidationProviderResolver previousValidationProviderResolver = null;

    /**
     * Map between a bundle and its validation provider.
     */
    private Map<Bundle, ValidationProvider<?>> bundlesProviders = null;
    
    /**
     * The bundle context.
     */
    private BundleContext bundleContext = null;

    /**
     * Default constructor.
     */
    public ValidationProviderActivator() {
        this.validationProviderResolver = new ValidationProviderResolverImpl();
        this.bundlesProviders = new WeakHashMap<Bundle, ValidationProvider<?>>();
    }

    /**
     * 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 validation provider resolver
        previousValidationProviderResolver = ValidationProviderResolverHolder.getValidationProviderResolver();
        ValidationProviderResolverHolder.setValidationProviderResolver(validationProviderResolver);

        // Some validation providers are already here ?
        ServiceReference[] serviceReferences = this.bundleContext.getServiceReferences(ValidationProvider.class.getName(), null);
        if (serviceReferences != null) {
            for (ServiceReference serviceReference : serviceReferences) {
                ValidationProvider<?> validationProvider = (ValidationProvider<?>) bundleContext.getService(serviceReference);
                bundlesProviders.put(serviceReference.getBundle(), validationProvider);
                validationProviderResolver.addValidationProvider(null, validationProvider);
            }
        }
        
        // Notification when new bundles are added on the platform
        bundleContext.addBundleListener(this);

        // Check to be notified when there are new implementations that are registered
        bundleContext.addServiceListener(this, "(objectClass=" + ValidationProvider.class.getName() + ")");
        
        
        // Also check if no META-INF/services/javax.validation.spi.ValidationProvider is available in the given bundles
        Bundle[] bundles = bundleContext.getBundles();
        if (bundles != null) {
            for (Bundle bundle : bundles) {
                loadBundle(bundle);
            }
              
        }
    }

    /**
     * Try to load a Validation Provider in the given bundle.
     * @param bundle the given bundle
     */
    protected void loadBundle(Bundle bundle) {
        URL url = bundle.getEntry(ValidationProviderResolverImpl.METAINF_SERVICES_VALIDATION_PROVIDER);
        // Load the provider if there is an URL
        if (url != null) {
            if (bundlesProviders.containsKey(bundle)) {
                return;
            }
            ValidationProvider<?> validationProvider = validationProviderResolver.getProvider(url, bundle, null);
            bundlesProviders.put(bundle, validationProvider);
            validationProviderResolver.addValidationProvider(url, validationProvider);
        }
    }
    
    
    /**
     * 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
        ValidationProviderResolverHolder.setValidationProviderResolver(previousValidationProviderResolver);
        
        // Remove all entries
        bundlesProviders.clear();
        validationProviderResolver.clearCachedProviders();
        
        
    }
    
    /**
     * 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();
        ValidationProvider<?> validationProvider = (ValidationProvider<?>) this.bundleContext.getService(serviceRef);

            switch (event.getType()) {
            case ServiceEvent.REGISTERED:
                if (!bundlesProviders.containsKey(serviceRef.getBundle())) {
                    bundlesProviders.put(serviceRef.getBundle(), validationProvider);
                    this.validationProviderResolver.addValidationProvider(null, validationProvider);
                }
                break;
            case ServiceEvent.UNREGISTERING:
                if (bundlesProviders.containsKey(serviceRef.getBundle())) {
                    validationProvider = bundlesProviders.remove(serviceRef.getBundle());
                    this.validationProviderResolver.removeValidationProvider(null, validationProvider);
                }
                break;
            default:
                break;
            }
        }
    
    /**
     * Unload a bundle and its associated validation provider.
     * @param bundle the given bundle
     */
    public void unloadBundle(Bundle bundle) {
        if (this.bundlesProviders.containsKey(bundle)) {
            URL url = bundle.getEntry(ValidationProviderResolverImpl.METAINF_SERVICES_VALIDATION_PROVIDER);
            ValidationProvider<?> validationProvider = bundlesProviders.remove(bundle);
            this.validationProviderResolver.removeValidationProvider(url, validationProvider);
        }
    }
    

    /**
     * Notified when bundle are changing.
     * @param event the bundle event
     */
    @Override
    public void bundleChanged(BundleEvent event) {
        if (event == null) {
            return;
        }
        Bundle bundle = event.getBundle();
        if (BundleEvent.RESOLVED == event.getType()) {
            loadBundle(bundle);
        } else if (BundleEvent.UNINSTALLED == event.getType() || BundleEvent.UNRESOLVED == event.getType()) {
            unloadBundle(bundle);
        }
        
        
    }

}
