package com.cerveza.togglefunction.activities;

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.support.wearable.view.DismissOverlayView;
import android.util.Log;
import android.widget.TextView;

import com.cerveza.togglefunction.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
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.OnMapReadyCallback;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.wearable.Wearable;

public class MapsActivity extends WearableActivity implements OnMapReadyCallback,GoogleMap.OnMapLongClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private MapFragment mapFragment;
    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    float zoomLevel = (float) 16.0;
    TextView textViewLatLng;
    private DismissOverlayView mDismissOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAmbientEnabled();
        setContentView(R.layout.activity_maps);
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mDismissOverlay =
                (DismissOverlayView) findViewById(R.id.dismiss_overlay);
        //mDismissOverlay.setIntroText(R.string.basic_wear_long_press_intro);
        //mDismissOverlay.showIntroIfNecessary();
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        textViewLatLng = (TextView) findViewById(R.id.textViewLatLong);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapLongClick(LatLng point) {
        mDismissOverlay.show();
    }

    @Override
    public void onEnterAmbient(Bundle ambientDetails) {
        super.onEnterAmbient(ambientDetails);
        mapFragment.onEnterAmbient(ambientDetails);
    }

    public void onExitAmbient() {
        super.onExitAmbient();
        mapFragment.onExitAmbient();
    }


    /**
     * 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. In this case,
     * we just add a marker near Sydney, Australia.
     * 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;
        mMap.setOnMapLongClickListener(this);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.moveCamera(CameraUpdateFactory.zoomBy(zoomLevel));
    }

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

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

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        LocationRequest locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(15000)
                .setFastestInterval(3000);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: notify that service is not available;
            return;
        }
        LocationServices.FusedLocationApi
                .requestLocationUpdates(mGoogleApiClient, locationRequest, this)
                .setResultCallback(new ResultCallback() {

                    @Override
                    public void onResult(@NonNull Result result) {
                        Status status = result.getStatus();
                        if (status.isSuccess()) {
                            if (Log.isLoggable("MapsActivity", Log.DEBUG)) {
                                Log.d("MapsActivity", "Successfully requested location updates");
                            }
                        } else {
                            Log.e("MapsActivity",
                                    "Failed in requesting location updates, "
                                            + "status code: "
                                            + status.getStatusCode()
                                            + ", message: "
                                            + status.getStatusMessage());
                        }
                    }
                });

        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        //mMap.moveCamera(CameraUpdateFactory.zoomBy(zoomLevel));
        if(lastLocation != null){
            //LatLng latLng = new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude());
            setLatLngTextView(lastLocation);
            //setMapPosition(latLng);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        if (Log.isLoggable(this.getClass().getName(), Log.DEBUG)) {
            Log.d(this.getClass().getName(), "connection to location client suspended");
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        if (!mGoogleApiClient.isConnected()) {
            return;
        }
       /* zoomLevel =  mMap.getCameraPosition().zoom;
        LatLng currentLocation = new LatLng(location.getLatitude(),location.getLongitude());
        setMapPosition(currentLocation);*/
        setLatLngTextView(location);


    }

    private void setMapPosition(LatLng currentLocation){
        CircleOptions circle = new CircleOptions().center(currentLocation).radius(20-zoomLevel);
        mMap.clear();
        mMap.addCircle(circle);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentLocation,zoomLevel);
        mMap.moveCamera(cameraUpdate);

    }

    private void setLatLngTextView(Location location){
        textViewLatLng.setText(String.format("Lat: %.5f, Lng: %.5f",location.getLatitude(),location.getLongitude()));
    }

}
