package com.example.patrice.rerservation01;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

// https://chantisandroid.blogspot.fr/2017/06/get-current-location-example-in-android.html

// http://www.androidsnippets.com/calculate-distance-between-two-gps-coordinates.html

// https://www.movable-type.co.uk/scripts/latlong.html

public class gps_location_02 extends AppCompatActivity
{

    private static final int REQUEST_LOCATION = 1;
    Button button;
    TextView textView;
    LocationManager locationManager;
    String latitude,longitude;

    SharedPreferences sharedpreferences;
    //public static final String appli_preference = "prefs";
    public static final String position_gps = "position_ONsemi";

    double distance_maxi = 500.00;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.current_gps_loaction);

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        textView = (TextView)findViewById(R.id.textView1);

        sharedpreferences = getSharedPreferences("PREFERENCE",  Context.MODE_PRIVATE);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
        {
            buildAlertMessageNoGps();
        }

        else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
        {
            getLocation();
        }

    }

//                 Onsemi à Basso Cambo
//                43.56 27 18
//                1.38 68  64


    //https://gps-coordinates.org/distance-between-coordinates.php

    // https://andrew.hedges.name/experiments/haversine/

    private void getLocation()
    {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)   != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(gps_location_02.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        }

        else
        {
            Location location_gps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location location_network = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            //Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

            if (location_gps != null)
            {
                double lat_gps = location_gps.getLatitude();
                double long_gps = location_gps.getLongitude();
                latitude = String.valueOf(lat_gps);
                longitude = String.valueOf(long_gps);

                double d = gps_distance_metres(lat_gps, long_gps, 43.562718 , 1.386864);
                double d2 = CalculationByDistance(lat_gps, long_gps, 43.562718 , 1.386864);

                textView.setText("Géolocalisation par GPS :"
                        + "\n" + "Lat = " + latitude
                        + "\n" + "Long = " + longitude
                        + "\n" + "d = " + d
                        + "\n" + "d2 = " + d2
                );

                if(d < distance_maxi)
                {
                    Toast.makeText(this,"Dans les locaux !. ",Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(position_gps, "inside");
                    editor.commit();
                }
                else
                {
                    Toast.makeText(this," > 500 métres , donc trop loin de ONsemi",Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(position_gps, "outside");
                    editor.commit();
                }

            }

            else if (location_network != null)
            {
                double lat_network = location_network.getLatitude();
                double long_network = location_network.getLongitude();
                latitude = String.valueOf(lat_network);
                longitude = String.valueOf(long_network);

                double d = gps_distance_metres(lat_network, long_network, 43.562718 , 1.386864);
                double d2 = CalculationByDistance(lat_network, long_network, 43.562718 , 1.386864);

                textView.setText("Géolocalisation à partir du réseau GSM :"
                        + "\n" + "Lat = " + latitude
                        + "\n" + "Long = " + longitude
                        + "\n" + "d = " + d
                        + "\n" + "d2 = " + d2
                );

                if(d < distance_maxi)
                {
                    Toast.makeText(this,"Dans les locaux !. ",Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(position_gps, "inside");
                    editor.commit();
                }
                else
                {
                    Toast.makeText(this," > 500 métres , donc trop loin de ONsemi",Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(position_gps, "outside");
                    editor.commit();
                }

            }
/*
            else  if (location2 != null)
            {
                double lat3 = location2.getLatitude();
                double long3 = location2.getLongitude();
                lattitude = String.valueOf(lat3);
                longitude = String.valueOf(long3);

                double d = gps2m(lat3, long3, 43.562718 , 1.386864);

                textView.setText("Your current location is"
                        + "\n" + "Lattitude = " + lattitude
                        + "\n" + "Longitude = " + longitude
                        + "\n" + "d = " + d);

              //  textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
              //          + "\n" + "Longitude = " + longitude);

            }
*/
            else
            {
                Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();
            }
        }
    }

    protected void buildAlertMessageNoGps()
    {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage("Veuillez activer votre GPS (turn ON) ")
                .setCancelable(false)

                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    public void onClick(final DialogInterface dialog, final int id)
                    {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })

                .setNegativeButton("No", new DialogInterface.OnClickListener()
                {
                    public void onClick(final DialogInterface dialog, final int id)
                    {
                        dialog.cancel();
                    }
                });

        final AlertDialog alert = builder.create();
        alert.show();
    }

    private double gps_distance_metres(double lat_a, double lng_a, double lat_b, double lng_b)
    {

        double pk = (double) (180/3.14169);

        double a1 = lat_a / pk;
        double a2 = lng_a / pk;
        double b1 = lat_b / pk;
        double b2 = lng_b / pk;

        double t1 = Math.cos(a1)*Math.cos(a2)*Math.cos(b1)*Math.cos(b2);
        double t2 = Math.cos(a1)*Math.sin(a2)*Math.cos(b1)*Math.sin(b2);
        double t3 = Math.sin(a1)*Math.sin(b1);
        double tt = Math.acos(t1 + t2 + t3);


        return 6366000*tt;
    }

/********/
    public double CalculationByDistance(double initialLat, double initialLong,   double finalLat, double finalLong)
    {
        int R = 6371; // km (Earth radius)
        double dLat = toRadians(finalLat-initialLat);
        double dLon = toRadians(finalLong-initialLong);
        initialLat = toRadians(initialLat);
        finalLat = toRadians(finalLat);

        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(initialLat) * Math.cos(finalLat);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c;
    }

    public double toRadians(double deg) {
        return deg * (Math.PI/180);
    }
/********/

}
