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

import java.io.IOException;

import org.osgi.framework.BundleContext;
import com.buglabs.application.AbstractServiceTracker;
import com.buglabs.bug.module.lcd.pub.ILCDModuleControl;
import com.buglabs.device.IButtonEventListener;
import com.buglabs.device.IButtonEventProvider;
import com.buglabs.device.ButtonEvent;


 /**
 *	Service tracker for the BugApp Bundle;
 *
 */
public class LCDbrightServiceTracker extends AbstractServiceTracker implements 
		IButtonEventListener {	

	private IButtonEventProvider buttonEventProvider;
	private ILCDModuleControl lcd;
	private int val = 0;

	
	public LCDbrightServiceTracker(BundleContext context) {
		super(context);
	}
	
	/**
	 * Determines if the application can start.
	 */
	public boolean canStart() {
		return super.canStart();
	}
	
	/**
	 * If canStart returns true
     * this method is called to start the application.
     * Place your fun logic here. 
	 */
	public void doStart() {
		System.out.println("LCDbackliteServiceTracker: start");
		buttonEventProvider = (IButtonEventProvider) getService(IButtonEventProvider.class);
		buttonEventProvider.addListener(this);
		lcd = (ILCDModuleControl)getService(ILCDModuleControl.class);
	}

	/**
	 * Called when a service that this application depends is unregistered.
	 */
	public void doStop() {
		buttonEventProvider.removeListener(this);
		System.out.println("LCDbackliteServiceTracker: stop");

	}

	/**
	 * 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().add("com.buglabs.bug.module.lcd.pub.ILCDModuleControl");
		getServices().add("com.buglabs.device.IButtonEventProvider");
	}
	
	public void buttonEvent(ButtonEvent event) {
		if (event.getAction() == ButtonEvent.KEY_UP) {
			System.out.println("Recieved button event...");
			switch (event.getButton()) {
			case ButtonEvent.BUTTON_HOTKEY_1:
				setBl(0);
				break;
			case ButtonEvent.BUTTON_HOTKEY_2:
				setBl(1);
				break;
			case ButtonEvent.BUTTON_HOTKEY_3:
				setBl(3);
				break;
			case ButtonEvent.BUTTON_HOTKEY_4:
				setBl(2);
				break;
			default:
			System.out.println("Unable to set Backlight...");
			}
		}
	}
	
	private void setBl(int i) {
		val = i;
		try {
			lcd.setBackLight(val);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}