/*
 * Decompiled with CFR 0.152.
 * 
 * Could not load the following classes:
 *  org.osgi.framework.Bundle
 *  org.osgi.framework.BundleActivator
 *  org.osgi.framework.BundleContext
 *  org.osgi.framework.BundleEvent
 *  org.osgi.framework.BundleListener
 *  org.osgi.framework.SynchronousBundleListener
 */
package org.apache.logging.log4j.core.config.plugins.osgi;

import java.util.concurrent.atomic.AtomicReference;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
import org.apache.logging.log4j.core.util.BundleResourceLoader;
import org.apache.logging.log4j.status.StatusLogger;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.SynchronousBundleListener;

public final class Activator
implements BundleActivator,
SynchronousBundleListener {
    private static final Logger LOGGER = StatusLogger.getLogger();
    private final AtomicReference<BundleContext> context = new AtomicReference();

    public void start(BundleContext context) throws Exception {
        if (this.context.compareAndSet(null, context)) {
            context.addBundleListener((BundleListener)this);
            Activator.scanInstalledBundlesForPlugins(context);
        }
    }

    private static void scanInstalledBundlesForPlugins(BundleContext context) {
        Bundle[] bundles;
        for (Bundle bundle : bundles = context.getBundles()) {
            if (bundle.getState() != 32) continue;
            Activator.scanBundleForPlugins(bundle);
        }
    }

    private static void scanBundleForPlugins(Bundle bundle) {
        LOGGER.trace("Scanning bundle [{}] for plugins.", bundle.getSymbolicName());
        PluginManager.loadPlugins(new BundleResourceLoader(bundle));
    }

    public void stop(BundleContext context) throws Exception {
        this.context.compareAndSet(context, null);
    }

    public void bundleChanged(BundleEvent event) {
        switch (event.getType()) {
            case 2: {
                Activator.scanBundleForPlugins(event.getBundle());
                break;
            }
        }
    }
}
