package com.atlassian.stash.internal.plugin.info;

import com.atlassian.analytics.api.services.AnalyticsConfigService;
import com.atlassian.bitbucket.plugin.OptionalPluginInformationProvider;
import org.eclipse.gemini.blueprint.context.BundleContextAware;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;

public class DefaultPluginInformationProvider implements BundleContextAware, DisposableBean, OptionalPluginInformationProvider {

    private static final Logger log = LoggerFactory.getLogger(DefaultPluginInformationProvider.class);

    private ServiceTracker serviceTracker;

    @Override
    public boolean canCollectAnalytics() {
        if (serviceTracker == null) {
            log.warn("serviceTracker is unexpectedly null");
            return false;
        }

        AnalyticsConfigService analyticsConfigService = (AnalyticsConfigService) serviceTracker.getService();
        if (analyticsConfigService != null) {
            //Check if analytics is enabled using the Analytics Plugins own Interface.
            return analyticsConfigService.canCollectAnalytics();
        } else {
            log.debug("No instance of the analyticsConfigService was found.");
            return false;
        }
    }

    @Override
    public void setBundleContext(BundleContext bundleContext) {
        serviceTracker = new ServiceTracker(bundleContext, AnalyticsConfigService.class.getName(), null);
        serviceTracker.open();
    }

    @Override
    public void destroy() throws Exception {
        if (serviceTracker != null) {
            serviceTracker.close();
        }
    }
}
