package gpslogger;

import org.osgi.framework.BundleContext;

import com.buglabs.application.AbstractServiceTracker;
import com.buglabs.bug.module.gps.pub.IPositionProvider;
import com.buglabs.bug.module.lcd.pub.IModuleDisplay;

/**
 * Our two headed friend that: specifies the services we
 * need from to be available before we can really start;
 * and gets notified by OSGI when the services are available
 * and starts us up when they are.
 * 
 * @author finsprings
 *
 */
public class MyServiceTracker extends AbstractServiceTracker {
	/**
	 * This is where all our interesting stuff is; the object that
	 * contains our actual application if you will. We own it
	 * because we're the ones that get to know when the services
	 * have become available that our application needs.
	 */
	private MyApplication myApplication;

	/**
	 * Our constructor. In our case, we don't need to do anything
	 * other than pass the BundleContext onto our base class'
	 * constructor.
	 * 
	 * @param context
	 */
	public MyServiceTracker( BundleContext context ) {
		super( context );
	}
	
	/**
	 * Called by the OSGI ServiceTracker to see if we think
	 * we can start yet. We don't really need to override
	 * this, other than to log it. You'll see this get called
	 * each time you add a module to the BUG.
	 */
	public boolean canStart() {
		System.out.println("GpsLogger: Can Start? " + super.canStart());
		return super.canStart();
	}
	
	/**
	 * Called once we've returned true from canStart(). This is
	 * where we start up our actual application.
	 */
	public void doStart() {
		System.out.println("GpsLogger service tracker: starting app now services are available");
		
		myApplication = new MyApplication(
				(IModuleDisplay) getService( IModuleDisplay.class ),
				(IPositionProvider) getService( IPositionProvider.class ) );
		myApplication.start();
		
		System.out.println("GpsLogger service tracker: started");
	}

	/**
	 * Called when a service that this application depends is unregistered.
	 * Without all of the services we need, we can't keep running, so
	 * stop our app.
	 */
	public void doStop() {
		System.out.println("GpsLogger: service tracker: stopping app now not all services are available");
		myApplication.stop();
		
		// help the garbage collector out a bit by be clear that we're done
		// with our application object at this point
		myApplication = null;
		System.out.println("GpsLogger: service tracker: stopped");
	}

	/**
	 * Here we build up the list of services that we need to be
	 * running before we can start up fully. Our Activator uses
	 * this information via a call to getServices() to create the
	 * filter it passes to the OSGI ServiceTracker.
	 */
	public void initServices() {
		getServices().add("com.buglabs.bug.module.gps.pub.IPositionProvider");
		getServices().add("com.buglabs.bug.module.lcd.pub.IModuleDisplay");
	}
}