package it.unipr.dsg.tracker;

import it.unipr.dsg.tracker.LocationTrackingService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	public static String TAG = "LocalizationService-b";
	private Button startButton = null;
	private Button stopButton;
	private Activity mContext = null;
	private Button showLastLocationButton = null;	
	private TextView locationTextView = null;
	protected LocationTrackingService mService = null;

	
	//ServiceConnection class to manage the binding with the service
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className,IBinder service) {
			// We've bound to LocalService, cast the IBinder and get LocalService instance
			LocalBinder binder = (LocalBinder) service;
			mService  = binder.getService();
		}
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mService = null;
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		this.mContext  = this;
		
		///////////////////////// UI Setup ////////////////////////////////////
		
		locationTextView = (TextView)findViewById(R.id.locationTextView);

		startButton  = (Button)findViewById(R.id.startButton);
		startButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				//Create the intent and bind to the Service
				Intent intent = new Intent(mContext, LocationTrackingService.class);
				bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
			}

		});

		stopButton = (Button)findViewById(R.id.stopButton);
		stopButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				//Unbind from the service if it was correctly bound
				if(mService != null)
					unbindService(mConnection);
			}
		});

		showLastLocationButton  = (Button)findViewById(R.id.showLastLocationButton);
		showLastLocationButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(mService != null)
				{
					//Call a method directly from the service instance
					Location lastLocation = mService.getCurrentLocation();
					
					locationTextView.setText("lat:"+lastLocation.getLatitude()+" / lng:" + lastLocation.getLongitude());

				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		
		if(mService != null)
			unbindService(mConnection);
		
		super.onDestroy();
	}


}