package com.example.patrice.rerservation01;

import android.Manifest;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.patrice.rerservation01.service_alarm.appli_alarm_service;

// Android 4: développement d'applications avancées Par Reto Meier

// https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

public class Main02 extends AppCompatActivity implements View.OnClickListener
{
    Button btn_acquisition_barcode,btn_listview_all_games_in_db, btn_restituer, btn_historique, btn_config,btn_quit;
    TextView tv_utilisateur;

    SharedPreferences.Editor editor;

    public static final String key_nom_utilisateur = "nom_utilisateur";

    private sharedPreference sharedpreferences;

    private static final int REQUEST_LOCATION = 1;

    LocationManager locationManager;
    String latitude,longitude;

    public static final String position_gps = "position_ONsemi";

    double distance_maxi = 500.00;

    boolean debug_mode = true;

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

        connexion_gps();

        tv_utilisateur = (TextView) findViewById(R.id.tv_utilisateur);

        ///// mode debug pour effacer
      //  settings = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
      //  editor = settings.edit();
      //  editor.remove("isFirstRun");
      //  editor.commit();

        SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("PREFERENCE", 0); // 0 - for private mode
        Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE) .getBoolean("isFirstRun", true);
        //   RESET pour le debug
        //   getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", true).commit();

        // premier run on doit valider l'enregristrement du client
        if (isFirstRun)
        {
            startActivity(new Intent(Main02.this, creation_compte.class));
            // avant de quitter l'activité creation_compte on lance le appli_alarm_service pour scruter les retours
        }

        // affiche le nom du client
        String nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);
        tv_utilisateur.setText(nom_uilisateur + " connected");

        ActionBar actionBar = getSupportActionBar(); // or getActionBar();
        getSupportActionBar().setTitle("   Ludo ONsemi"); // set the top title
        String title = actionBar.getTitle().toString(); // get the title
        //actionBar.hide(); // or even hide the actionbar

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.drawable.appli_icon);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

        btn_acquisition_barcode = (Button) findViewById(R.id.btn_acquisition_barcode);
        btn_acquisition_barcode.setOnClickListener(this);

        btn_restituer = (Button) findViewById(R.id.btn_restituer);
        btn_restituer.setOnClickListener(this);

        btn_listview_all_games_in_db = (Button) findViewById(R.id.btn_listview_all_games_in_db);
        btn_listview_all_games_in_db.setOnClickListener(this);

        btn_historique = (Button) findViewById(R.id.btn_historique);
        btn_historique.setOnClickListener(this);

        btn_config = (Button) findViewById(R.id.btn_config);
        btn_config.setOnClickListener(this);

        btn_quit = (Button) findViewById(R.id.btn_quit);
        btn_quit.setOnClickListener(this);

        /************************************************************************/

        boolean network_status = isConnectedToNetwork();

        if (!isNetworkAvailable()) // pour le debug on supprime la négation !
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Réseau Internet non disponible ! \n \n Veuillez réessayer plus tard.")
                    .setIcon(R.drawable.network)
                    .setTitle("Connexion ?.")
                    .setCancelable(false)
                    .setPositiveButton("Quitter", new DialogInterface.OnClickListener()
                    {
                                public void onClick(DialogInterface dialog, int id)
                                {
                                    // Restart the Activity
                                    //Intent intent = getIntent();
                                    finish();
                                    //startActivity(intent);
                                }
                    });

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

    }

    /************************************************************************/

    @Override
    public void onClick(View V)
    {
        int id = V.getId();
        Intent i;

        switch(id)
        {
            case R.id.btn_acquisition_barcode:
                Toast.makeText(this, "New version...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), traitement_scanner03.class);
                startActivity(i);

                //debug coco = new debug();
                //coco.debug();
                break;

            case R.id.btn_listview_all_games_in_db:
                i = new Intent(getApplicationContext(), listview_all_games_in_db_06.class);
//              i = new Intent(getApplicationContext(), listview_all_games.class);
//              i = new Intent(getApplicationContext(), progress_dialog.class);
                startActivity(i);
                break;

            case R.id.btn_restituer:
                Toast.makeText(this, "restituer...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), restituer_jeu.class);
                startActivity(i);
                break;

            case R.id.btn_historique:
                //i = new Intent(getApplicationContext(), mes_emprunts04.class);
                i = new Intent(getApplicationContext(), historique_retrait_jeu.class);
                startActivity(i);
                break;

            case R.id.btn_config:
                Toast.makeText(this, "Options...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), options.class);
                //i = new Intent(getApplicationContext(), action_bar.class);
                //i = new Intent(getApplicationContext(), retrait_01.class);
                startActivity(i);
                break;
            case R.id.btn_quit:
                //quitter_confirmation();
                //i = new Intent(getApplicationContext(), statistiques_02.class);
                i = new Intent(getApplicationContext(), retrait_01.class);

                startActivity(i);
                break;

        }
    }

    /************************************************************************/

    private boolean isConnectedToNetwork()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

    /************************************************************************/

    // Private class isNetworkAvailable
    private boolean isNetworkAvailable()
    {
        // Using ConnectivityManager to check for Network Connection
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

    /************************************************************************/

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /************************************************************************/
    // menu dans la l'action bar
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        Intent i;

        switch (item.getItemId())
        {

            case R.id.item1:
                i = new Intent(getApplicationContext(), aide.class);
                startActivity(i);
                break;

            case R.id.item2:
                about();
                break;

/*

            case R.id.item1:
                Toast.makeText(this, "Liste des jeux...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), liste_jeux_db.class);
                startActivity(i);
                break;

            case R.id.item2:
                Toast.makeText(this, "Scanner le code bar... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), scanner_barcode08.class);
                //i = new Intent(getApplicationContext(), ajouter_jeu.class);
                startActivity(i);
                break;
            case R.id.item3:
                Toast.makeText(this, "Scanner le code bar... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), scanner_barcode09.class);
                //i = new Intent(getApplicationContext(), ajouter_jeu.class);
                startActivity(i);
                break;

            case R.id.item4:
                Toast.makeText(this, "Mes emprunts... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), mes_emprunts04.class);
                startActivity(i);
                break;
            case R.id.item5:
                Toast.makeText(this, "Pamamétres...", Toast.LENGTH_LONG).show();
                //i = new Intent(getApplicationContext(), mes_emprunts04.class);
                i = new Intent(getApplicationContext(), SignUpActivity.class);
                startActivity(i);
                break;

            case R.id.item6:
                Toast.makeText(this, "Item5...", Toast.LENGTH_LONG).show();
                //i = new Intent(getApplicationContext(), listview001.class);
                i = new Intent(getApplicationContext(), user_inscription.class);
                startActivity(i);
                break;

            case R.id.item7:
                Toast.makeText(this, "Item7...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), capture01.class);
                startActivity(i);
                break;

            case R.id.item8:
                Toast.makeText(this, "Item8 - Gestion DB02", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), gestion_DB03.class);
                startActivity(i);
                break;

            case R.id.item9:
                //Toast.makeText(this, "Item8...", Toast.LENGTH_LONG).show();
                //i = new Intent(getApplicationContext(), capture06.class);  // capture01 par défaut
                //startActivity(i);
                Toast.makeText(this, "Item9 - about", Toast.LENGTH_LONG).show();
                about();
                break;

            case R.id.item10:
                //Toast.makeText(this, "Salut...", Toast.LENGTH_LONG).show();
                //i = new Intent(getApplicationContext(), acceuil.class);  // capture01 par défaut
                //startActivity(i);
                Toast.makeText(this, "Item10 - quitter", Toast.LENGTH_LONG).show();
                quitter_confirmation();
                break;

            case android.R.id.home:
                //Toast.makeText(this, "Retour button...", Toast.LENGTH_LONG).show();
                // app icon in action bar clicked; goto parent activity.
                quitter_confirmation();
                //this.finish();
                //return true;
*/
        }

        return super.onOptionsItemSelected(item);
    }

    /************************************************************************/

    public void about()
    {
        final Dialog dialog = new Dialog(Main02.this);

        dialog.setContentView(R.layout.about_layout);
        dialog.setTitle("About:");
        dialog.show();

        Button dialogCloseButton = (Button) dialog.findViewById(R.id.close_button);

        dialogCloseButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.dismiss();
            }
        });

    }

    /************************************************************************/

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

        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
    /************************************************************************/

    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(Main02.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);

            if (location_gps != null)
            {

                SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("PREFERENCE", 0); // 0 - for private mode

                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);

                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();
                    dialog_infos_gps();

                }

            }

            else if (location_network != null)
            {

                SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("PREFERENCE", 0); // 0 - for private mode

                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);


                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();
                    dialog_infos_gps();

                }

            }

            else
            {
                Toast.makeText(this,"Impossible de tracer votre géolocalisation par GPS !!!",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();
    }

    /************************************************************************/

    protected  void dialog_infos_gps()
    {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        alertDialogBuilder.setTitle("Informations position GPS:");

        alertDialogBuilder
                .setMessage("Vous devez être sur le site de ONsemi pour rendre un jeu !.")
                .setIcon(R.drawable.map)
                .setCancelable(false)
                .setNegativeButton("Fermer",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

    /************************************************************************/

    //haversine
    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);
    }

    /************************************************************************/

    public void quitter_confirmation()
    {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        alertDialogBuilder.setTitle("Confirmation");

        alertDialogBuilder
                .setMessage("Appuyer sur Oui pour quitter l'appli !.")
                .setCancelable(false)
                .setPositiveButton("Oui",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        Toast.makeText(Main02.this, "A bientôt ...", Toast.LENGTH_LONG).show();
                        //Main02.this.finish();
                        Main02.this.finishAffinity();
                        System.exit(0);
                    }
                })

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

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    /************************************************************************/
/*

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }
*/

    public void onBackPressed()
    {
        //super.onBackPressed();
        //finish();
        //System.exit(0);
        //moveTaskToBack(true);

        quitter_confirmation();
    }

     /************************************************************************/

}


