package com.example.tracker;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class TrackerMapActivity extends Activity { //API11+
  private GoogleMap map;
  private Polyline polyLine;
  private ArrayList<LatLng> points = new ArrayList<LatLng>();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_layout);

        MapFragment mapFragment = ((MapFragment) getFragmentManager() //API11+
        .findFragmentById(R.id.mapFragment));
    map = mapFragment.getMap();
    if (map == null) {
      return;
    }

    // Retrieve the ArrayList of Locations from the Intent extras
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    ArrayList<Location> locations = extras.getParcelableArrayList("locations");

    Location firstPoint = locations.get(0);
    LatLng latLng = new LatLng(firstPoint.getLatitude(),
                               firstPoint.getLongitude());
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

    map.addMarker(new MarkerOptions()
        .position(latLng)
        .title("Start")
        .snippet(latLng.toString())
        .icon(
            BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
    Location lastPoint = locations.get(locations.size()-1);
    latLng = new LatLng(lastPoint.getLatitude(), lastPoint.getLongitude());
    map.addMarker(new MarkerOptions()
        .position(latLng)
        .title("Start")
        .snippet(latLng.toString())
        .icon(
            BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

    for (int i = 0; i < locations.size(); i++) {
      Location location = locations.get(i);
      points.add(new LatLng(location.getLatitude(), location.getLongitude()));
    }
    PolylineOptions polylineOptions = new PolylineOptions();
    polylineOptions.width(3).color(0xff0000ff).addAll(points).geodesic(true);
    if (TrackerMapActivity.this.polyLine != null) {
      TrackerMapActivity.this.polyLine.remove();
    }
    TrackerMapActivity.this.polyLine = map.addPolyline(polylineOptions);
  }

}