package gpslogger;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.util.tracker.ServiceTracker;

import com.buglabs.util.ServiceFilterGenerator;

/**
 * The activator is the main 'hook' for our bundle. When
 * the BUG loads our bundle it will call Activator.start().
 * Similarly, when the BUG unloads our bundle it will call
 * Activator.stop().
 * 
 * @author finsprings
 *
 */
public class MyActivator implements BundleActivator {
	/**
	 * This is our helper that we use to:
	 * 1) Specify the services that our bundle needs before it can run
	 * 2) Provide a callback to the OSGI framework so we can be nformed when
	 *    services we need become available. 
	 */
	private MyServiceTracker myServiceTracker;
	
	/**
	 * This is the underlying OSGI object that will actually
	 * track services for us as they become available and get
	 * taken away (as other bundles get loaded and unloaded).
	 */
	private ServiceTracker osgiServiceTracker;
	
	/**
	 * This is where we start out our lives us a bundle. We
	 * can start ourselves here if we don't need any other
	 * services. Since in this case we know we do (otherwise
	 * we wouldn't have bothered setting up that customizer),
	 * so we need to tell the framework what services we need.
	 * Once we've done that we just have to sit back and wait
	 * until those services get loaded.
	 */
	public void start( BundleContext context ) throws Exception {
		System.out.println( "GpsLogger: activator start" );
		
		// create our service tracker; we couldn't do
		// it earlier since it needs the context
		myServiceTracker = new MyServiceTracker( context );
		
		// create the filter that the OSGI ServiceTracker will use
		// to determine the services we care to be informed about.
		final Filter f = context.createFilter(
				ServiceFilterGenerator.generateServiceFilter(
						myServiceTracker.getServices() ) );
		
		// create the OSGI ServiceTracker; the object that will actually
		// track services for us.
		osgiServiceTracker = new ServiceTracker(context, f, myServiceTracker);
		osgiServiceTracker.open();
		
		// now we will be in limbo until the services we need arrive
		// (unless they are already available of course, in which
		// case our service tracker will be getting doStart() called
		// on it shortly.
		System.out.println( "GpsLogger: activator started" );
	}

	/**
	 * This is our last call before biting the dust. We need to
	 * stop all background threads, close DB connections, free up
	 * resources, and all the good stuff.
	 */
	public void stop(BundleContext context) throws Exception {
		System.out.println( "GpsLogger: activator stop" );
		
		// tell the OSGI ServiceTracker to stop tracking services for us
		osgiServiceTracker.close();
		
		// get our service tracker to shut the app down
		myServiceTracker.stop();
		
		System.out.println( "GpsLogger: activator stopped" );
	}
}