package cgeo.geocaching;

import cgeo.geocaching.playservices.LocationProvider;
import cgeo.geocaching.sensors.DirectionProvider;
import cgeo.geocaching.sensors.GeoDataProvider;
import cgeo.geocaching.sensors.GpsStatusProvider;
import cgeo.geocaching.sensors.GpsStatusProvider.Status;
import cgeo.geocaching.sensors.IGeoData;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.OOMDumpingUncaughtExceptionHandler;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

import rx.Observable;
import rx.functions.Action1;

import android.app.Application;
import android.view.ViewConfiguration;

import java.lang.reflect.Field;

public class CgeoApplication extends Application {

    private boolean forceRelog = false; // c:geo needs to log into cache providers
    public boolean showLoginToast = true; //login toast shown just once.
    private boolean liveMapHintShownInThisSession = false; // livemap hint has been shown
    private static CgeoApplication instance;
    private Observable<IGeoData> geoDataObservable;
    private Observable<Float> directionObservable;
    private Observable<Status> gpsStatusObservable;
    private volatile IGeoData currentGeo = null;
    private volatile float currentDirection = 0.0f;
    private boolean isGooglePlayServicesAvailable = false;

    public static void dumpOnOutOfMemory(final boolean enable) {

        if (enable) {

            if (!OOMDumpingUncaughtExceptionHandler.activateHandler()) {
                Log.e("OOM dumping handler not activated (either a problem occured or it was already active)");
            }
        } else {
            if (!OOMDumpingUncaughtExceptionHandler.resetToDefault()) {
                Log.e("OOM dumping handler not resetted (either a problem occured or it was not active)");
            }
        }
    }

    public CgeoApplication() {
        setInstance(this);
    }

    private static void setInstance(final CgeoApplication application) {
        instance = application;
    }

    public static CgeoApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        try {
            final ViewConfiguration config = ViewConfiguration.get(this);
            final Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException ignore) {
        }
        // ensure initialization of lists
        DataStore.getLists();
        // Check if Google Play services is available
        if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
            isGooglePlayServicesAvailable = true;
        }
        Log.i("Google Play services are " + (isGooglePlayServicesAvailable ? "" : "not ") + "available");
        geoDataObservable = (isGooglePlayServicesAvailable() ? LocationProvider.create(this) : GeoDataProvider.create(this))
                .replay(1).refCount().doOnNext(new Action1<IGeoData>() {
                    @Override
                    public void call(final IGeoData geoData) {
                        currentGeo = geoData;
                    }
                });

        directionObservable = DirectionProvider.create(this).replay(1).refCount().doOnNext(new Action1<Float>() {
            @Override
            public void call(final Float direction) {
                currentDirection = direction;
            }
        });
        gpsStatusObservable = GpsStatusProvider.create(this).share();
    }

    @Override
    public void onLowMemory() {
        Log.i("Cleaning applications cache.");
        DataStore.removeAllFromCache();
    }

    public Observable<IGeoData> geoDataObservable() {
        return geoDataObservable;
    }

    public Observable<Float> directionObservable() {
        return directionObservable;
    }

    public Observable<Status> gpsStatusObservable() {
        if (gpsStatusObservable == null) {
            gpsStatusObservable = GpsStatusProvider.create(this).share();
        }
        return gpsStatusObservable;
    }

    public IGeoData currentGeo() {
        return currentGeo != null ? currentGeo : geoDataObservable().toBlocking().first();
    }

    public Float distanceNonBlocking(final ICoordinates target) {
        if (currentGeo == null || target.getCoords() == null) {
            return null;
        }
        return currentGeo.getCoords().distanceTo(target);
    }

    public float currentDirection() {
        return currentDirection;
    }

    public boolean isLiveMapHintShownInThisSession() {
        return liveMapHintShownInThisSession;
    }

    public void setLiveMapHintShownInThisSession() {
        liveMapHintShownInThisSession = true;
    }

    /**
     * Check if cgeo must relog even if already logged in.
     *
     * @return <code>true</code> if it is necessary to relog
     */
    public boolean mustRelog() {
        final boolean mustLogin = forceRelog;
        forceRelog = false;
        return mustLogin;
    }

    /**
     * Force cgeo to relog when reaching the main activity.
     */
    public void forceRelog() {
        forceRelog = true;
    }

    public boolean isGooglePlayServicesAvailable() {
        return isGooglePlayServicesAvailable;
    }

}

@@ -115,32 +115,72 @@
 ectionProvider;%0A
+import cgeo.geocaching.sensors.GeoData;%0A
 import cgeo.geoc
@@ -457,16 +457,54 @@
 Handler;
+%0Aimport cgeo.geocaching.utils.RxUtils;
 %0A%0Aimport
@@ -1312,20 +1312,39 @@
 ntGeo = 
-null
+GeoData.dummyLocation()
 ;%0A    pr
@@ -3057,24 +3057,240 @@
 vailable%22);%0A
+        final Action1%3CIGeoData%3E rememberGeoData = new Action1%3CIGeoData%3E() %7B%0A            @Override%0A            public void call(final IGeoData geoData) %7B%0A                currentGeo = geoData;%0A            %7D%0A        %7D;%0A
         geoD
@@ -3453,33 +3453,25 @@
 ext(
-new Action1%3CI
+remember
 GeoData
-%3E() %7B
+);
 %0A   
@@ -3479,182 +3479,108 @@
     
-            @Override%0A                    public void call(final IGeoData geoData) %7B%0A                        currentGeo = geoData;%0A                    %7D%0A                %7D
+geoDataObservable.subscribeOn(RxUtils.looperCallbacksScheduler).first().subscribe(rememberGeoData
 );%0A
-%0A
     
@@ -4533,72 +4533,8 @@
 tGeo
- != null ? currentGeo : geoDataObservable().toBlocking().first()
 ;%0A  
@@ -4620,30 +4620,8 @@
 if (
-currentGeo == null %7C%7C 
 targ

fix #4180: ANR in CacheListActivity