package com.example.tracker;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    private Location currentLocation;
    private LocationListener locationListener;
    private LocationManager locationManager;
    private ArrayList<Location> locations = new ArrayList<Location>();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationManager = (LocationManager) 
                getSystemService(Context.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                if (location != null) {
                    locations.add(location);
                    String label = getResources().getString(
                            R.string.numLocations);
                    setStatusText(label + " " + locations.size());

                    currentLocation = location;
                    displayLocation();
                }
            }
            public void onStatusChanged(String provider, int status,
                    Bundle extras) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };

        Button startTracking = (Button) findViewById(R.id.buttonStartTracking);
        startTracking.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 0,
                        locationListener);

                String text = getResources().getString(
                        R.string.startTrackingMessage);
                setStatusText(text);
            }
        });

        Button stopTracking = (Button) findViewById(R.id.buttonStopTracking);
        stopTracking.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                locationManager.removeUpdates(locationListener);

                String text = getResources().getString(
                        R.string.stopTrackingMessage);
                setStatusText(text);
            }
        });

        Button clearTracking = (Button) findViewById(R.id.buttonClearTracking);
        clearTracking.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                locations.clear();

                String text = getResources().getString(
                        R.string.clearTrackingMessage);
                setStatusText(text);
            }
        });

        Button totalDistance = (Button) findViewById(R.id.buttonTotalDistanceTraveled);
        totalDistance.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                float totalMeters = 0.0F;

                // Compute and display the total distance traveled
                // between all of the locations in the cache
                totalMeters = getDistanceTraveled(locations);

                String text = getMetersFormattedString(totalMeters);
                setStatusText(text);
            }
        });

        Button mapMovements = (Button) findViewById(R.id.buttonMapMovements);
        mapMovements.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if  (locations.size() == 0) {
                    return;
                }

                // Pass the ArrayList of Location objects to the 
                // MapActivity by adding it the Intent's extras Bundle
                Intent intent = new Intent(MainActivity.this,
                        TrackerMapActivity.class);
                Bundle extras = new Bundle();
                extras.putParcelableArrayList("locations", locations);
                intent.putExtras(extras);
                startActivity(intent);
            }
        });
    }

    private void displayLocation() {
        if (currentLocation != null) {
            Resources resource = getResources();
            TextView tvLocation = 
                    (TextView) findViewById(R.id.textViewLocation);
            tvLocation.setText(resource.getString(R.string.location)
                    + " " + currentLocation.getLatitude()
                    + ", " + currentLocation.getLongitude());
        }
    }

    private String getMetersFormattedString(float meters) {
        String pattern = "###,###,##0.00";
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String metersString = myFormatter.format(meters);

        Resources resources = getResources();
        String text = resources.getString(R.string.distance) + " "
                + metersString + " "
                + resources.getString(R.string.meters);
        return text;
    }

    private void setStatusText(String status) {
        TextView tvStatus = 
                (TextView) findViewById(R.id.textViewStatus);
        tvStatus.setText(status);
    }

    private float getDistanceTraveled(List<Location> list) {
        float totalMeters = 0;
        if (list.size() > 1) {
            for (int i = 1; i < list.size(); i++) {
                Location prevLocation = list.get(i - 1);
                Location currLocation = list.get(i);
                if (prevLocation != null && currLocation != null) {
                    totalMeters += currLocation
                            .distanceTo(prevLocation);
                }
            }
        }
        return totalMeters;
    }
}
