package it.unipr.mobdev.tracker;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class LocationTrackingService extends Service implements LocationListener {

	private LocationManager locationManager = null;
	private Location currentLocation = null;
	private int ONGOING_NOTIFICATION = 1111;

	@Override
	public IBinder onBind(Intent arg0) {
		Log.d(MainActivity.TAG, "LocationTrackingService ---> onBind()");
		
		//Return null since we do not have (and do not want in this case) a bound service
		return null;
	}

	@Override
	public void onCreate() {
		Log.d(MainActivity.TAG, "LocationTrackingService ---> onCreate()");

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.d(MainActivity.TAG, "LocationTrackingService ---> onDestroy()");
		super.onDestroy();

		if (locationManager != null) {
			locationManager.removeUpdates(this);
			locationManager = null;
		}

		stopForeground(true);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(MainActivity.TAG, "LocationTrackingService ---> onStartCommand()");
		startServiceTask();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.d(MainActivity.TAG, "LocationTrackingService ---> onUnbind()");
		return super.onUnbind(intent);
	}

	public void startServiceTask() {
		Log.d(MainActivity.TAG,	"LocationTrackingService ---> Starting LocationTrackingService");

		//Show the notification and set the service as foreground to prevent it to be destroyed by the OS
		setServiceAsForeground();

		// Acquire a reference to the system Location Manager
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Log.d(MainActivity.TAG, "GPS_PROVIDER is ebabled !");

			Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

			if (lastKnownLocation != null)
				updateLocation(lastKnownLocation);

			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		} else
			Toast.makeText(this, "GPS is not ebabled !", Toast.LENGTH_LONG).show();

		if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			Log.d(MainActivity.TAG, "NETWORK_PROVIDER is ebabled !");

			Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

			if (lastKnownLocation != null)
				updateLocation(lastKnownLocation);

			// Register the listener with the Location Manager to receive
			// location updates
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		}
	}

	/*
	 * OLD METHOD WITH OLD NOTIFICATION MANAGAMENT
	private void setServiceAsForeground()
	{
		Log.d(MainActivity.TAG, "LocationTrackingService ---> setServiceAsForeground()");

		Notification notification = new Notification(R.drawable.icon_notification_exclamation_mark,"Location Service Running ...",System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.setLatestEventInfo(this,"Location Service","Running ...", pendingIntent);

		startForeground(ONGOING_NOTIFICATION, notification);
	}
	 */

	private void setServiceAsForeground()
	{
		Log.d(MainActivity.TAG, "LocationTrackingService ---> setServiceAsForeground()");
		
		// Prepare the intent triggered if the notification is selected
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

		// Build the notification
		// Use NotificationCompat.Builder instead of just Notification.Builder to support older Android versions
		Notification notification  = new NotificationCompat.Builder(this)
		.setContentTitle("Localization Service")
		.setContentText("Running ...")
		.setSmallIcon(R.drawable.icon_notification_exclamation_mark)
		.setContentIntent(pIntent)
		.setAutoCancel(true).build();
		
		//Start the service as foreground
		startForeground(ONGOING_NOTIFICATION, notification);
	}

	/*** LocationListener Methods ***/
	@Override
	public void onLocationChanged(Location location) {
		Log.d(MainActivity.TAG,
				"LocationTrackingService ---> onLocationChanged(): Provider: "
						+ location.getProvider() + " Lat: "
						+ location.getLatitude() + " Lng: "
						+ location.getLongitude() + " Accuracy: "
						+ location.getAccuracy());
		updateLocation(location);
	}

	private void updateLocation(Location location) {
		Log.d(MainActivity.TAG,
				"LocationTrackingService ---> onLocationChanged(): Updating Location ... ");

		currentLocation = location;

		Intent broadcast = new Intent();
		broadcast.setAction("it.unipr.dsg.tracker.NEW_LOCATION");
		Bundle bundle = new Bundle();
		bundle.putDouble("lat", currentLocation.getLatitude());
		bundle.putDouble("lng", currentLocation.getLongitude());
		broadcast.putExtras(bundle);
		sendBroadcast(broadcast);
	}

	@Override
	public void onProviderDisabled(String arg0) {
		Log.d(MainActivity.TAG,
				"LocationTrackingService ---> onProviderDisabled()");
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.d(MainActivity.TAG,
				"LocationTrackingService ---> onProviderEnabled()");
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.d(MainActivity.TAG,
				"LocationTrackingService ---> onStatusChanged()");
	}

	/***********************************/
}
