/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dhaval.android.appstat.service;

import android.content.Context;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
import com.dhaval.android.appstat.model.*;

/**
 *
 * @author dhaval
 */
public class LocationManager {

    private static final long UPDATE_TIME = 0;
    private static final long UPDATE_DISTANCE = 0;
    private Context context;

    private Location currentLocation = new Location(0, 0, "Citylight, Surat, Gujarat, India");

    public LocationManager(final Context context) {
        this.context = context;
    }

    public void start(){
        try{
            // Acquire a reference to the system Location Manager
            android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            // Define a listener that responds to location updates
            LocationListener locationListener = new LocationListener() {

                public void onLocationChanged(android.location.Location location) {
                    // Called when a new location is found by the network location provider.
                    updateLocation(location);
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                public void onProviderEnabled(String provider) {
                    Toast.makeText(context, provider + " found", Toast.LENGTH_SHORT);
                }

                public void onProviderDisabled(String provider) {
                }
            };

            // Register the listener with the Location Manager to receive location updates
            locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, UPDATE_TIME, UPDATE_DISTANCE, locationListener);
            locationManager.requestLocationUpdates(android.location.LocationManager.NETWORK_PROVIDER, UPDATE_TIME, UPDATE_DISTANCE, locationListener);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private void updateLocation(android.location.Location location){
        if(currentLocation == null){
            currentLocation = new Location(location.getLatitude(), location.getLongitude(), "");
        }else{
            currentLocation.setLan(location.getLongitude());
            currentLocation.setLat(location.getLatitude());
        }

//        Toast.makeText(context, "Lan: " + location.getLongitude() + ", Lat: " + location.getLatitude(), Toast.LENGTH_SHORT);
    }

    public Location getLocation(){
        return currentLocation;
    }
}
