/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.loader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.BundleTracker;

/**
 * This class will track all META-INF/ resources (except MANIFEST) so that we can get URL for META-INF/services/* key for example.
 * @author Florent Benoit
 */
public class MetaInfScanner implements IMetaInfLocator {

    /**
     * BundleContext.
     */
    private final  BundleContext bundleContext;

    /**
     * Bundle Tracker.
     */
    private BundleTracker bundleTracker;

    /**
     * Registration of the locator service.
     */
    private ServiceRegistration<?> metaInfLocatorService;

    /**
     * Bundle Customizer used to track entries in bundles.
     */
    private MetaInfScannerBundleTrackerCustomizer metaInfScannerBundleTrackerCustomizer = null;

    /**
     * Default constructor for the given bundle context.
     * @param bundleContext the bundle context
     */
    public MetaInfScanner(final BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    /**
     * Register the service when we start.
     * So we will track META-INF/ entries
     */
    public void start() {
        this.metaInfLocatorService = this.bundleContext.registerService(IMetaInfLocator.class.getName(), this, null);
        this.metaInfScannerBundleTrackerCustomizer = new MetaInfScannerBundleTrackerCustomizer(this.bundleContext);

        // Start the OSGi JDBC Driver tracker
        this.bundleTracker = new BundleTracker(this.bundleContext, Bundle.ACTIVE, this.metaInfScannerBundleTrackerCustomizer);
        this.bundleTracker.open();
    }


    /**
     * Stop the locator and stop tracking entries.
     */
    public void stop() {
        if (this.metaInfLocatorService != null) {
            this.metaInfLocatorService.unregister();
        }
        this.bundleTracker.close();
    }

    /**
     * Gets an URL for a given resource name.
     * @param name the name to search
     * @return value else null if not found
     */
    @Override
    public URL getResource(final String name) {
        List<URL> urls = this.metaInfScannerBundleTrackerCustomizer.getEntries(name);
        if (urls != null) {
            return urls.get(0);
        }
        return null;
    }

    /**
     * Gets inputstream for the given name.
     * @param name the name to search
     * @return value else null if not found
     */
    @Override
    public InputStream getResourceAsStream(final String name) {
        List<URL> urls = this.metaInfScannerBundleTrackerCustomizer.getEntries(name);
        if (urls != null) {
            try {
                return urls.get(0).openStream();
            } catch (IOException e) {
                throw new IllegalArgumentException("Cannot get stream", e);
            }
        }
        return null;
    }

    /**
     * Gets list of URL for the given resource name.
     * @param name the name to search
     * @return value else null if not found
     * @throws IOException if there is an error while searching entry
     */
    @Override
    public Enumeration<URL> getResources(final String name) throws IOException {
        List<URL> urls = this.metaInfScannerBundleTrackerCustomizer.getEntries(name);
        if (urls != null) {
            Vector<URL> collectionURLs = new Vector<URL>();
            collectionURLs.addAll(urls);
            return collectionURLs.elements();
        }
        return null;

    }
}
