package indoor.java;

import android.app.IntentService;
import android.content.ComponentName;
import android.content.Intent;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

import it.cnr.isti.steplogger.IStepLoggerService;


/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 */
public class StepLoggerClient {

	private static StepLoggerClient instance;

	// Intent Service fields
	private static String LOG_TAG = "StepLoggerClient";
	private boolean mustRun = true;

	// Bound Service fields
	final String BOUNDSERVICE_PACKAGE = "it.cnr.isti.steplogger";
	final String BOUNDSERVICE_CLASS = ".StepLoggerService";
	IStepLoggerService mService;

	Boolean isBound = false;
	Intent intentService = new Intent();

	//Bound Service Connection
	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder boundService) {
			mService = IStepLoggerService.Stub.asInterface((IBinder) boundService);
			Log.d(LOG_TAG, "onServiceConnected() : OK ");
			isBound = true;
		}

	    public void onServiceDisconnected(ComponentName name) {
			mService = null;
			Log.d(LOG_TAG, "onServiceDisconnected() : OK ");
			isBound = false;
		}

	};

    /** ctor */
	public StepLoggerClient(MyActivity act) {

		instance = this;

		intentService.setClassName(BOUNDSERVICE_PACKAGE, BOUNDSERVICE_PACKAGE + BOUNDSERVICE_CLASS);
		act.bindService(intentService, mConnection , Context.BIND_AUTO_CREATE );

	}

    /** static access from C++ */
	public static int log(double x, double y, double z) {
		Log.d("me", "got values");
		return instance._log(x,y,z);
	}

    private int _log(double x, double y, double z) {
		Log.d("me", mService + "");
		if (mService == null) {return 0;}
		try {
			mService.logPosition(System.currentTimeMillis(), x, y, z);
			return 1337;
		} catch (final Exception e) {
		    return 0;
		}
	}

}
