package com.example.olive.gps;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap = null;
    private Marker merkki = null;
    private double Lat;
    private double Lng;
    private LocationListener listener;
    int permissionCheck;
    private LocationManager locationManager;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionCheck = +this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            Log.d(TAG, "PermissionCheck1: " + permissionCheck);
            if (permissionCheck != 0) {
                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
            } else {
                Log.d(TAG, "No need to check location permissions");
            }
        }

        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        assert mapFragment != null;
        mapFragment.getMapAsync(this);

        myListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        permissionCheck = 0;
        //Log.d(TAG, "Version: " + Build.VERSION.SDK_INT + " Your: " + Build.VERSION_CODES.M);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionCheck = +this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            //Log.d(TAG, "PermissionCheck2: " + permissionCheck);
        }
        if(permissionCheck == 0) {
            //Log.d(TAG, "Listener");
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            assert locationManager != null;
            if(mMap != null){
                lastLocation();
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        assert locationManager != null;
        locationManager.removeUpdates(listener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        assert locationManager != null;
        locationManager.removeUpdates(listener);
    }

    @SuppressLint("MissingPermission")
    private void lastLocation(){
        if(locationManager.getLastKnownLocation("gps") != null){
            //Log.d(TAG, "Last location: " + locationManager.getLastKnownLocation("gps"));
            Location location1 = locationManager.getLastKnownLocation(("gps"));
            Lat = location1.getLatitude();
            Lng = location1.getLongitude();
            if(mMap != null){
                if(merkki != null){
                    merkki.remove();
                }
                LatLng position = new LatLng(Lat, Lng);
                merkki = mMap.addMarker(new MarkerOptions().position(position).title("Marker"));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 17));
            }
        }
    }

    private void myListener(){
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Lat = location.getLatitude();
                Lng = location.getLongitude();
                if (mMap != null && Lng != 0.0 && Lat != 0.0) {
                    if (merkki != null) {
                        merkki.remove();
                    }
                    LatLng position = new LatLng(Lat, Lng);
                    merkki = mMap.addMarker(new MarkerOptions().position(position).title("Marker"));
                    //Numero on zoomauskerroin
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 17));
                    updateCameraBearing(mMap, location.getBearing());
                    //minZoomLevel = mMap.getMinZoomLevel();
                    Log.d(TAG, "Location: " + Lat + " " + Lng);
                }
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

                Log.d(TAG, "StatusChanged");
                Log.d(TAG, s);
            }

            @Override
            public void onProviderEnabled(String s) {
                Log.d(TAG, "ProviderEnabled");
                Log.d(TAG, s);
            }

            @Override
            public void onProviderDisabled(String s) {
                Log.d(TAG, "ProviderDisabled");
                Log.d(TAG, s);
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(i);
            }
        };
    }

    private void updateCameraBearing(GoogleMap googleMap, float bearing) {
        if ( googleMap == null) return;
        CameraPosition camPos = CameraPosition
                .builder(
                        googleMap.getCameraPosition() // current Camera
                )
                .bearing(bearing)
                .build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
    }
    /**
     * 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;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            //Log.d(TAG, "Check: " + permissionCheck);
            if (permissionCheck == 0) {
                lastLocation();
            }
        }
        else {
            lastLocation();

        }
    }
}
