package com.anders.reride.gms;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsResult;

import static com.google.android.gms.location.LocationServices.FusedLocationApi;

/**
 * Class for retrieving current GPS position
 */

public class LocationService extends Service
        implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener{
    private static final String TAG = LocationSubscriberService.class.getCanonicalName();

    //Request keys
    public static final int REQUEST_CHECK_SETTINGS = 1;
    public static final int REQUEST_CHECK_CONNECTION = 2;

    //Actions
    public static final String ACTION_CONNECTED =
            "com.example.anders.flexsensor.gms.LocationSubscriberService.ACTION_CONNECTED";
    public static final String ACTION_CONNECTION_FAILED =
            "com.example.anders.flexsensor.gms.LocationSubscriberService.ACTION_CONNECTION_FAILED";

    //Intent keys
    public static final String ERROR_STRING_KEY =
            "com.example.anders.flexsensor.gms.LocationSubscriberService.ERROR_STRING_KEY";

    //Location API
    private GoogleApiClient mGoogleApiClient;
    private PendingResult<LocationSettingsResult> mLocationSettingsResult;

    private final IBinder binder = new LocationService.LocalBinder();

    @Override
    public void onCreate() {
        super.onCreate();

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

    }

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(String action, Parcelable result) {
        final Intent intent = new Intent(action);
        intent.putExtra(ERROR_STRING_KEY, result);
        sendBroadcast(intent);
    }

    public class LocalBinder extends Binder {
        public LocationService getService() {
            return LocationService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        connect();
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        disconnect();
        Log.d(TAG, "Disconnected");
        return super.onUnbind(intent);
    }

    public void connect() {
        mGoogleApiClient.connect();
        Log.d(TAG, "Connected");
    }

    public void disconnect() {
        mGoogleApiClient.disconnect();
        Log.d(TAG, "Disconnected");
    }


    public Location getLocation() {
        //TODO: Return location
        try {
             Location location = FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            Log.d(TAG, "Retrieved location info");
            return location;
        } catch (SecurityException e) {
            return null;
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        broadcastUpdate(ACTION_CONNECTED);
    }

    @Override
    public void onConnectionSuspended(int cause) {
        switch (cause) {
            case CAUSE_NETWORK_LOST:
                //TODO: Try to reconnect network
                break;
            case CAUSE_SERVICE_DISCONNECTED:
                //TODO: Try to reconnect service
                break;
            default:
                Log.d(TAG, "Unknown cause on connection suspended");
                break;
        }

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG, connectionResult.getErrorMessage());
        if (connectionResult.getErrorCode() == ConnectionResult.RESOLUTION_REQUIRED) {
            broadcastUpdate(ACTION_CONNECTION_FAILED, connectionResult);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

@@ -53,16 +53,48 @@
 ervice;%0A
+import android.content.Context;%0A
 import a
@@ -831,32 +831,8 @@
 ice 
-extends Service%0A        
 impl
@@ -927,16 +927,17 @@
 stener%7B%0A
+%0A
     priv
@@ -1027,611 +1027,75 @@
     
-//Request keys%0A    public static final int REQUEST_CHECK_SETTINGS = 1;%0A    public static final int REQUEST_CHECK_CONNECTION = 2;%0A%0A    //Actions%0A    public static final String ACTION_CONNECTED =%0A            %22com.examp
+private boo
 le
-.
 an
-ders.flexsensor.gms.LocationSubscriberService.ACTION_CONNECTED%22;%0A    public static final String ACTION_CONNECTION_FAILED =%0A            %22com.examp
+ mRequiresResolution;%0A    private boo
 le
-.
 an
-ders.flexsensor.gms.LocationSubscriberService.ACTION_CONNECTION_FAILED%22;%0A%0A    //Intent keys%0A    public static final String ERROR_STRING_KEY =%0A            %22com.example.anders.flexsensor.gms.LocationSubscriberService.ERROR_STRING_KEY%22
+ mConnected
 ;%0A%0A 
@@ -1238,148 +1238,54 @@
 t;%0A%0A
+%0A
     p
-rivate final IBinder binder = new LocationService.LocalBinder();%0A%0A    @Override%0A    public void onCreate() %7B%0A        super.onCreate();%0A
+ublic LocationService(Context context) %7B
 %0A   
@@ -1430,20 +1430,23 @@
 Builder(
-this
+context
 )%0A      
@@ -1648,793 +1648,8 @@
  %7D%0A%0A
-    private void broadcastUpdate(final String action) %7B%0A        final Intent intent = new Intent(action);%0A        sendBroadcast(intent);%0A    %7D%0A%0A    private void broadcastUpdate(String action, Parcelable result) %7B%0A        final Intent intent = new Intent(action);%0A        intent.putExtra(ERROR_STRING_KEY, result);%0A        sendBroadcast(intent);%0A    %7D%0A%0A    public class LocalBinder extends Binder %7B%0A        public LocationService getService() %7B%0A            return LocationService.this;%0A        %7D%0A    %7D%0A%0A    @Nullable%0A    @Override%0A    public IBinder onBind(Intent intent) %7B%0A        connect();%0A        return binder;%0A    %7D%0A%0A    @Override%0A    public boolean onUnbind(Intent intent) %7B%0A        disconnect();%0A        Log.d(TAG, %22Disconnected%22);%0A        return super.onUnbind(intent);%0A    %7D%0A%0A
     
@@ -2293,41 +2293,62 @@
     
-broadcastUpdate(ACTION_CONNECTED)
+mConnected = true;%0A        mRequiresResolution = false
 ;%0A  
@@ -2409,32 +2409,60 @@
 ed(int cause) %7B%0A
+        mConnected = false;%0A
         switch (
@@ -2918,24 +2918,52 @@
 onResult) %7B%0A
+        mConnected = false;%0A
         Log.
@@ -3109,67 +3109,34 @@
     
-broadcastUpdate(ACTION_CONNECTION_FAILED, connectionResult)
+mRequiresResolution = true
 ;%0A  
@@ -3154,78 +3154,155 @@
  %7D%0A%0A
-%0A
     
-@Override%0A    public void onDestroy() %7B%0A        super.onDestroy()
+public boolean isRequiresResolution() %7B%0A        return mRequiresResolution;%0A    %7D%0A%0A    public boolean isConnected() %7B%0A        return mConnected
 ;%0A  

Remove Service implementation