/*
 * Copyright 2013 - 2014 Anton Tananaev (anton.tananaev@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.traccar.client;

import java.util.Date;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;

public class PositionProvider {

    public static final String PROVIDER_MIXED = "mixed";
    public static final long PERIOD_DELTA = 10 * 1000;
    public static final long RETRY_PERIOD = 60 * 1000;

    public interface PositionListener {
        public void onPositionUpdate(Location location);
    }
    
    private final Handler handler;
    private final LocationManager locationManager;
    private final long period;
    private final PositionListener listener;

    private boolean useFine;
    private boolean useCoarse;

    public PositionProvider(Context context, String type, long period, PositionListener listener) {
        handler = new Handler(context.getMainLooper());
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        this.period = period;
        this.listener = listener;

        // Determine providers
        if (type.equals(PROVIDER_MIXED)) {
            useFine = true;
            useCoarse = true;
        } else if (type.equals(LocationManager.GPS_PROVIDER)) {
            useFine = true;
        } else if (type.equals(LocationManager.NETWORK_PROVIDER)) {
            useCoarse = true;
        }
    }

    public void startUpdates() {
        if (useFine) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, period, 0, fineLocationListener);
        }
        if (useCoarse) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, period, 0, coarseLocationListener);
        }
        handler.postDelayed(updateTask, period);
    }

    public void stopUpdates() {
        handler.removeCallbacks(updateTask);
        locationManager.removeUpdates(fineLocationListener);
        locationManager.removeUpdates(coarseLocationListener);
    }

    private final Runnable updateTask = new Runnable() {

        private boolean tryProvider(String provider) {
            Location location = locationManager.getLastKnownLocation(provider);
            
            if (location != null && new Date().getTime() - location.getTime() <= period + PERIOD_DELTA) {
                listener.onPositionUpdate(location);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void run() {
            if (useFine && tryProvider(LocationManager.GPS_PROVIDER)) {
            } else if (useCoarse && tryProvider(LocationManager.NETWORK_PROVIDER)) {
            } else {
                listener.onPositionUpdate(null);
            }
            handler.postDelayed(this, period);
        }

    };

    private final InternalLocationListener fineLocationListener = new InternalLocationListener();
    private final InternalLocationListener coarseLocationListener = new InternalLocationListener();

    private class InternalLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(final String provider, int status, Bundle extras) {
            if (status == LocationProvider.TEMPORARILY_UNAVAILABLE || status == LocationProvider.OUT_OF_SERVICE) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        locationManager.removeUpdates(InternalLocationListener.this);
                        locationManager.requestLocationUpdates(provider, period, 0, InternalLocationListener.this);
                    }
                }, RETRY_PERIOD);
            }
        }

    }

}

@@ -921,16 +921,45 @@
 Handler;
+%0Aimport android.widget.Toast;
 %0A%0Apublic
@@ -1418,24 +1418,59 @@
 er listener;
+%0A    private final Context context;
 %0A%0A    privat
@@ -1835,16 +1835,48 @@
 istener;
+%0A        this.context = context;
 %0A%0A      
@@ -2914,32 +2914,32 @@
 ing provider) %7B%0A
-
             Loca
@@ -2997,24 +2997,316 @@
 n(provider);
+%0A%0A            /*if (location != null) %7B%0A                Toast.makeText(context, %22phone: %22 + new Date() + %22%5Cngps: %22 + new Date(location.getTime()), Toast.LENGTH_LONG).show();%0A            %7D else %7B%0A                Toast.makeText(context, %22no location%22, Toast.LENGTH_LONG).show();%0A            %7D*/
 %0A           

Add debugging code