package cgeo.geocaching.maps.routing;

import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.utils.Log;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Xml;

import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public final class Routing {
    private static final double MAX_ROUTING_DISTANCE_KILOMETERS = 5.0;
    private static BRouterServiceConnection brouter;
    private static Geopoint lastDirectionUpdatePoint;
    private static Geopoint[] lastRoutingPoints;
    private static Geopoint lastDestination;

    private Routing() {
        // utility class
    }

    public static void connect() {
        if (brouter != null && brouter.isConnected()) {
            //already connected
            return;
        }

        brouter = new BRouterServiceConnection();
        final Intent intent = new Intent();
        intent.setClassName("btools.routingapp", "btools.routingapp.BRouterService");

        if (!getContext().bindService(intent, brouter, Context.BIND_AUTO_CREATE)) {
            brouter = null;
        }
    }

    private static ContextWrapper getContext() {
        return CgeoApplication.getInstance();
    }

    public static void disconnect() {
        if (brouter != null && brouter.isConnected()) {
            getContext().unbindService(brouter);
            brouter = null;
        }
    }

    @Nullable
    public static Geopoint[] getTrack(final Geopoint start, final Geopoint destination) {
        if (brouter == null) {
            return null;
        }

        // Disable routing for huge distances
        if (start.distanceTo(destination) > MAX_ROUTING_DISTANCE_KILOMETERS) {
            return null;
        }

        // Use cached route if current position has not changed more than 5m
        // TODO: Maybe adjust this to current zoomlevel
        if (lastDirectionUpdatePoint != null && destination == lastDestination && start.distanceTo(lastDirectionUpdatePoint) < 0.005) {
            return lastRoutingPoints;
        }

        // now really calculate a new route
        lastDestination = destination;
        lastRoutingPoints = calculateRouting(start, destination);
        lastDirectionUpdatePoint = start;
        return lastRoutingPoints;
    }

    private static Geopoint[] calculateRouting(final Geopoint start, final Geopoint dest) {
        final Bundle params = new Bundle();
        params.putString("trackFormat", "gpx");
        params.putDoubleArray("lats", new double[]{start.getLatitude(), dest.getLatitude()});
        params.putDoubleArray("lons", new double[]{start.getLongitude(), dest.getLongitude()});
        params.putString("v", Settings.getRoutingMode().parameterValue);

        final String gpx = brouter.getTrackFromParams(params);

        return parseGpxTrack(gpx);
    }

    @Nullable
    private static Geopoint[] parseGpxTrack(final String gpx) {
        try {
            final LinkedList<Geopoint> result = new LinkedList<>();
            Xml.parse(gpx, new DefaultHandler() {
                @Override
                public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException {
                    if (qName.equalsIgnoreCase("trkpt")) {
                        final String lat = atts.getValue("lat");
                        if (lat != null) {
                            final String lon = atts.getValue("lon");
                            if (lon != null) {
                                result.add(new Geopoint(lat, lon));
                            }
                        }
                    }
                }
            });

            return result.toArray(new Geopoint[result.size()]);

        } catch (final SAXException e) {
            Log.e("cannot parse brouter output", e);
        }
        return null;
    }

    public static void invalidateRouting() {
        lastDirectionUpdatePoint = null;
    }

    public static boolean isAvailable() {
        return brouter != null;
    }
}

@@ -592,45 +592,176 @@
 ble 
-MAX_ROUTING_DISTANCE_KILOMETERS = 5.0
+UPDATE_MIN_DISTANCE_KILOMETERS = 0.005;%0A    private static final double MAX_ROUTING_DISTANCE_KILOMETERS = 5.0;%0A    private static final int UPDATE_MIN_DELAY_SECONDS = 3
 ;%0A  
@@ -958,16 +958,56 @@
 ination;
+%0A    private static long timeLastUpdate;
 %0A%0A    pr
@@ -1973,32 +1973,254 @@
 ull;%0A        %7D%0A%0A
+        // avoid updating to frequently%0A        final long timeNow = System.currentTimeMillis();%0A        if ((timeNow - timeLastUpdate) %3C 1000 * UPDATE_MIN_DELAY_SECONDS) %7B%0A            return lastRoutingPoints;%0A        %7D%0A%0A
         // Disab
@@ -2624,21 +2624,46 @@
 oint) %3C 
-0.005
+UPDATE_MIN_DISTANCE_KILOMETERS
 ) %7B%0A    
@@ -2898,16 +2898,50 @@
  start;%0A
+        timeLastUpdate = timeNow;%0A
         
@@ -4609,32 +4609,32 @@
 dateRouting() %7B%0A
-
         lastDire
@@ -4654,24 +4654,52 @@
 int = null;%0A
+        timeLastUpdate = 0;%0A
     %7D%0A%0A    p

fix #6006: limit frequency of routing updates