public class GetLocationActivity extends FragmentActivity
    implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

  Item item = ItemController.getItem();

  private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

  private GoogleMap mMap;
  private GoogleApiClient mGoogleApiClient;
  private LocationRequest locationRequest;
  private Location location;
  public static final String TAG = GetLocationActivity.class.getSimpleName();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_location);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment =
        (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mGoogleApiClient =
        new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    locationRequest =
        LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000) // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds
  }

  @Override
  protected void onResume() {
    super.onResume();
    // setUpMapIfNeeded();
    mGoogleApiClient.connect();
  }

  @Override
  protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
      mGoogleApiClient.disconnect();
    }
  }

  @Override
  public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");
    location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
      LocationServices.FusedLocationApi.requestLocationUpdates(
          mGoogleApiClient, locationRequest, this);
    } else {
      handleNewLocation(location);
    }
  }

  private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    MarkerOptions options = new MarkerOptions().position(latLng);
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
  }

  @Override
  public void onConnectionSuspended(int i) {
    Log.i(TAG, "Location services suspended. Please reconnect.");
  }

  @Override
  public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
      try {
        // Start an Activity that tries to resolve the error
        connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
      } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
      }
    } else {
      Log.i(
          TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
  }

  /**
   * Manipulates the map once available. This callback is triggered when the map is ready to be
   * used. This is where we can add markers or lines, add listeners or move the camera. If Google
   * Play services is not installed on the device, the user will be prompted to install it inside
   * the SupportMapFragment. This method will only be triggered once the user has installed Google
   * Play services and returned to the app.
   */
  @Override
  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
  }

  @Override
  public void onLocationChanged(Location location) {
    handleNewLocation(location);
  }

  public void saveLocation(View view) {
    if (location != null) {
      Intent passBack = new Intent();
      Double latitude = location.getLatitude();
      Double longitude = location.getLongitude();
      passBack.putExtra("location", location);
      passBack.putExtra("latitude", latitude);
      passBack.putExtra("longitude", longitude);
      setResult(RESULT_OK, passBack);
    }
    finish();
  }

  public void cancelOut(View view) {
    finish();
  }
}