package com.example.patrice.rerservation01;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.speech.tts.TextToSpeech;
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.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;

// UI modéle http://abhiandroid.com/ui/button

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;


public class Main02 extends AppCompatActivity implements View.OnClickListener
{

    Button btn_acquisition_barcode;
    Button btn_listview_all_games_in_db;
    Button btn_restituer, btn_historique,btn_apropos, btn_config,btn_quit;
    TextView tv_utilisateur;

    SharedPreferences settings;
    SharedPreferences.Editor editor;

    // preferences
   // SharedPreferences sharedpreferences;
   // public static final String mypreference = "mypref";
    public static final String key_nom_utilisateur = "nom_utilisateur";

    private TextView txtSpeechInput;

    private final int REQ_CODE_SPEECH_INPUT = 100;

    private TextToSpeech tts;

    private TextToSpeech textToSpeech;
    private boolean ready;

  //  private sharedPreference sharedPreference;

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

/*
        textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()
        {
            @Override
            public void onInit(int status)
            {
                Log.e("TTS", "TextToSpeech.OnInitListener.onInit...");
                String toSpeak = "Salut Patoche petit essai vocale "; //editText_text.getText().toString();
                // A random String (Unique ID).
                String utteranceId = UUID.randomUUID().toString();
                textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
            }
        });
*/

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

        Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE) .getBoolean("isFirstRun", true);
        //   RESET pour le debug
        //   getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", true).commit();

        if (isFirstRun)
        {
            startActivity(new Intent(Main02.this, creation_compte.class));
            Toast.makeText(Main02.this, "First Run", Toast.LENGTH_LONG).show();
        }

        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("Emprunt 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);

        //getActionBar().setHomeButtonEnabled(true);
        //getActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // déporter dans l'activité SignUpActivity qui gére les préférences de l'utilisateur
        //getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", false).commit();

        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_apropos = (Button) findViewById(R.id.btn_apropos);
        btn_apropos.setOnClickListener(this);

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

  /*
        boolean network_status = isConnectedToNetwork();

        if (!isNetworkAvailable()) // pour le debug j'ai supprimer 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_05.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, "Config...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), options.class);
                startActivity(i);
                break;

            case R.id.btn_apropos:
                //about();
                i = new Intent(getApplicationContext(), gps_location_02.class);
                startActivity(i);
                break;

            case R.id.btn_quit:
                quitter_confirmation();
                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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        Intent i;

        switch (item.getItemId())
        {
            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();
            }
        });

    }


    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 void onBackPressed()
    {
        finish();
        System.exit(0);
    }
}


