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

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;

import org.osgi.framework.BundleContext;

import sun.io.MalformedInputException;

import com.buglabs.application.AbstractServiceTracker;
import com.buglabs.bug.module.gps.pub.INMEARawFeed;

/**
 *	Service tracker for the BugApp Bundle;
 *
 */
public class GpsTestServiceTracker extends AbstractServiceTracker {	

	private Thread t;
	private InputStream is;

	public GpsTestServiceTracker(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() {
		INMEARawFeed service = (INMEARawFeed) getService(INMEARawFeed.class);
		try {
			is = service.getInputStream();

			t = new Thread() {
				public void run() {
					System.out.println("GpsTestServiceTracker: start");

					try {
						String str = "";
						byte[] buff = new byte[20];

						int read = 0;
						while(!isInterrupted() && read != -1) {

							read = is.read(buff);
							if(read > 0) {
								System.out.write(buff, 0, read);
							}
						}
					} catch (MalformedInputException e) {
						System.err.println("Malformed input exception: ");
						e.printStackTrace();
					} catch (InterruptedIOException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							System.out.println("Closing input stream");
							is.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			};

			t.start();

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

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

		try {
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 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.gps.pub.INMEARawFeed");
	}
}