/**
 *	Generated by Dragonfly SDK
 *
 */
package camera.servicetracker;

import java.util.Iterator;

import org.osgi.framework.BundleContext;
import com.buglabs.application.AbstractServiceTracker;
import camera.*;

 /**
 *	Service tracker for the BugApp Bundle;
 *
 */
public class CameraServiceTracker extends AbstractServiceTracker {
	private CameraApplication application;	

	public CameraServiceTracker(BundleContext context) {
		super(context);
	}
	
	/**
	 * Determines if the application can start.
	 */
	// TODO: undo this override - only here to figure out why it won't start
	/*
	public boolean canStart() {
		return super.canStart();
	}
	*/
	public boolean canStart() {
		boolean ok = true;
		
		if (hasStarted()) {
			return false;
		}

		Iterator servicesIter = services.iterator();

		while (servicesIter.hasNext()) {
			final String serviceClassName = (String) servicesIter.next();
			try {
				if (getService(
						Class.forName(serviceClassName)) == null) {
					System.out.println("Still waiting for " + serviceClassName);
					ok = false;
				}				
			}
			catch (ClassNotFoundException e) {
				e.printStackTrace();
				ok = false;
			}
		}

		return ok;
	}	
	/**
	 * If canStart returns true
     * this method is called to start the application.
     * Place your fun logic here. 
	 */
	public void doStart() {
		if(!getApplication().isAlive()) {
			if(getApplication().getRan()) {
				application = new CameraApplication(this);
			}
			getApplication().start();
		}

	}

	/**
	 * Called when a service that this application depends is unregistered.
	 */
	public void doStop() {
		getApplication().tearDown();

	}

	/**
	 * Allows the user to set the service dependencies by
     * adding them to services list returned by getServices().
     * i.e.nl getServices().add(MyService.class.getName());
	 */
	public void initServices() {
		getServices().addAll(getApplication().getServices());
	}
	
	/**
	 * Returns the application thread.
	 */
	public CameraApplication getApplication() {
		if(application == null) {
			application = new CameraApplication(this);
		}
		
		return application;
	}
}