/*
 * Copyright 2009 OW2 Chameleon
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ow2.chameleon.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Core Activator launches Chameleon Core bundles.
 * <ol>
 * <li>iPOJO</li>
 * <li>File Install</li>
 * <li>Felix OSGi Compendium</li>
 * <li>Felix Configuration Admin</li>
 * </ol>
 * @author <a href="mailto:chameleon-dev@ow2.org">Chameleon Project Team</a>
 *
 */
public class CoreActivator implements BundleActivator {


    /**
     * iPOJO Prefix.
     */
    public static final String IPOJO = "org.apache.felix.ipojo-";

    /**
     * Config Admin Prefix.
     */
    public static final String CONFIG_ADMIN = "org.apache.felix.configadmin-";

    /**
     * FileInstall Prefix.
     */
    public static final String FILE_INSTALL = "org.apache.felix.fileinstall-";

    /**
     * Compendium Prefix.
     */
    public static final String COMPENDIUM = "org.osgi.compendium-";

    /**
     * Number of bundle composing the core.
     */
    public static final int COUNT = 4;

    /**
     * Core directory.
     */
    private File directory;

    /**
     * Initializes the Core activator.
     * @param dir the core directory
     */
    public CoreActivator(File dir) {
        directory = dir;
    }

    /**
     * Deploys and starts the core bundles.
     * Bundles are installed and then started.
     * @param bc bundle context
     * @throws Exception is the core activator cannot be started correctly.
     * @see org.osgi.framework.BundleActivator
     *  #start(org.osgi.framework.BundleContext)
     */
    public void start(BundleContext bc) throws Exception {
        Logger logger = LoggerFactory.getLogger(
                Chameleon.CHAMELEON_LOGGER_NAME);

        File[] files = directory.listFiles();
        int foundcount = 0;
        List bundles = new ArrayList();
        for (int i = 0; i < files.length; i++) {
            if (match(files[i].getAbsolutePath())) {
                logger.info("Installing " + files[i].getName());
                Bundle bundle = bc.installBundle(
                        "reference:" + files[i].toURI().toURL().toExternalForm());
                bundles.add(bundle);
                foundcount++;
            }
        }

        // Check that the three bundles were found.
        if (foundcount < COUNT) {
            throw new Exception("Cannot install core"
                    + " bundles : only " + foundcount
                    + " bundles found on " + COUNT);
        }

        for (int i = 0; i < bundles.size(); i++) {
            Bundle bundle = (Bundle) bundles.get(i);
            logger.info("Starting " + bundle.getSymbolicName());
            bundle.start();
        }

    }

    /**
     * Checks if the given path is one of the core bundle.
     * @param absolutePath the path
     * @return true if the path contains one of the core bundle
     *  prefix.
     */
    private boolean match(String absolutePath) {
        return StringUtils.contains(absolutePath, IPOJO)
                || StringUtils.contains(absolutePath, CONFIG_ADMIN)
                || StringUtils.contains(absolutePath, FILE_INSTALL)
                || StringUtils.contains(absolutePath, COMPENDIUM);
    }

    /**
     * Does nothing.
     * @param bc bundle context
     * @throws Exception never raised
     * @see org.osgi.framework.BundleActivator
     *  #stop(org.osgi.framework.BundleContext)
     */
    public void stop(BundleContext bc) throws Exception {
        // Nothing to do.
    }


}
