package it.unipr.mobdev.tracker;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
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-a";
	private Button startButton = null;
	private Button stopButton;
	private Activity mContext = null;
	private ActivityLocationTrackingReceiver activityLocationReceiver = null;
	private TextView locationTextView = null;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        this.mContext  = this;
        
        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 start the background Service
				Intent service = new Intent(mContext,LocationTrackingService.class);
				startService(service);
				
				/*
				Intent service = new Intent("it.unipr.dsg.tracker.LocationTrackingService.SERVICE");
				startService(service);
				*/
			}
		});
        
        stopButton = (Button)findViewById(R.id.stopButton);   
        stopButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent service = new Intent(mContext,LocationTrackingService.class);
				stopService(service);
			}
		});
        
        //If not exists create the broadcast receiver to get the call back from the Service
        if(activityLocationReceiver == null)
        {
        	Log.d(TAG,"Registering Activity Location Receiver");
        	activityLocationReceiver = new ActivityLocationTrackingReceiver();
        	this.registerReceiver(activityLocationReceiver, new IntentFilter("it.unipr.dsg.tracker.NEW_LOCATION"));
        }
        
    }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Intent service = new Intent(mContext,LocationTrackingService.class);
		
		if(activityLocationReceiver != null)
			unregisterReceiver(activityLocationReceiver);
		
		stopService(service);
	}
	
	public class ActivityLocationTrackingReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle extras = intent.getExtras();
			Log.d(MainActivity.TAG,"ActivityLocationTrackingReceiver ---> Received Intent: " + intent.getAction());
			double lat = extras.getDouble("lat");
			double lng = extras.getDouble("lng");
			
			//Update the UI
			locationTextView.setText("lat:"+ lat +" / lng:" + lng);
		}
	}

	
    
}