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.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.os.AsyncTask;
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.Toast;

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;


// http://www.semurjengkol.com/populating-android-listview-with-json-based-data-fetched-from-mysql-server-using-php/

// // http://abhiandroid.com/ui/textswitcher  plein d'example ++++++

public class MainActivity extends AppCompatActivity
{
    EditText UsernameEt, PasswordEt;
    Button register;

    public static final int CONNECTION_TIMEOUT=10000;
    public static final int READ_TIMEOUT=15000;

    public static boolean PORTRAIT_MODE = true;
    //OrientationEventListener myOrientationEventListener ;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UsernameEt = (EditText)findViewById(R.id.etUserName);
        PasswordEt = (EditText)findViewById(R.id.etPassword);
        register = (Button)findViewById(R.id.button);


        ActionBar actionBar = getSupportActionBar(); // or getActionBar();
        getSupportActionBar().setTitle("My new title"); // 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.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

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

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


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

        if (isFirstRun)
        {
            //show start activity

            startActivity(new Intent(MainActivity.this, SignUpActivity.class));
            Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG).show();
        }

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

/*
        SensorEventListener m_sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
                {
                    Log.i("TAG++++++++++++++++++","Orientation : PORTRAIT");
                    //Toast.makeText(this, "Liste des jeux...", Toast.LENGTH_LONG).show();

                }
                else {
                    Log.i("TAG++++++++++++++++++","Orientation : PORTRAIT");
                    //Toast.makeText(this, "Liste des jeux...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {}
        };
*/

/*
        myOrientationEventListener = new OrientationEventListener(this,    SensorManager.SENSOR_DELAY_NORMAL)
        {
            @Override
            public void onOrientationChanged(int orientation)
            {

                //PORTRAIT_MODE = ((orientation < 100) || (orientation > 280));
                //Log.w("+++++++Orient", orientation + " PORTRAIT_MODE = " + PORTRAIT_MODE);
                //Log.w("+++++++Orient", orientation + " PORTRAIT_MODE = " + PORTRAIT_MODE);

                if(orientation == 270)
                {
                    Toast.makeText(MainActivity.this, "couché", Toast.LENGTH_LONG).show();
                }
                else
                {
                  // 0 degré
                    Toast.makeText(MainActivity.this, "debout", Toast.LENGTH_LONG).show();
                }

            }
        };
        //Log.w("Listener", " can detect orientation: " + myOrientationEventListener.canDetectOrientation() + " ");
        myOrientationEventListener.enable();
*/
/*
        myOrientationEventListener = new OrientationEventListener(this,  SensorManager.SENSOR_DELAY_NORMAL)
        {
            @Override
            public void onOrientationChanged(int arg0)
            {
                myOrientationEventListener.enable();

                if ((arg0 < 100) || (arg0 > 280))
                {
                   // setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    Log.w("+++++++Orient", arg0 + " PORTRAIT_MODE = ");
                }
                else
                 {
                  //  setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                     Log.w("+++++++Orient", arg0 + " PORTRAIT_MODE = ");

                 }
            }
        };
*/
    }

    public void OnLogin(View view)
    {
        String username = UsernameEt.getText().toString();
        String password = PasswordEt.getText().toString();

        login_request instance_login = new login_request(this);
        instance_login.execute(username, password);
    }

    public class login_request extends AsyncTask<String,Void,String>
    {
        Context context;
        AlertDialog alertDialog;

        login_request (Context ctx)
        {
            context = ctx;
        }

        @Override
        protected String doInBackground(String... params)
        {
                String login_url = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/users_login.php";

                try
                {
                    String username = params[0];
                    String password = params[1];
                    URL url = new URL(login_url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

                    httpURLConnection.setReadTimeout(READ_TIMEOUT);
                    httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);

                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);

                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                    String post_data = URLEncoder.encode("txtUsername","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
                            +URLEncoder.encode("txtPassword","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");

                    bufferedWriter.write(post_data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();

                    // réponse du serveur php
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                    String result="";
                    String line="";

                    while((line = bufferedReader.readLine())!= null)
                    {
                        result += line;
                    }

                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    return result;
                }

                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }

                catch (IOException e)
                {
                    e.printStackTrace();
                }

            return null;
        }

        @Override
        protected void onPreExecute()
        {
            alertDialog = new AlertDialog.Builder(context).create();
            alertDialog.setTitle("Login Status");
        }

        @Override
        protected void onPostExecute(String result)
        {
            alertDialog.setMessage(result);
            alertDialog.show();
        }

        @Override
        protected void onProgressUpdate(Void... values)
        {
            super.onProgressUpdate(values);
        }
    }


    @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_DB02.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.
                this.finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void about()
    {

        //http://androidexample.com/Custom_Dialog_-_Android_Example/index.php?view=article_discription&aid=88

        final Dialog dialog = new Dialog(MainActivity.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)
            {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });

    }


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

        alertDialogBuilder.setTitle("Confirmation");

        alertDialogBuilder
                .setMessage("Apputer sur Oui pour quitter l'appli !.")
                .setCancelable(false)
                .setPositiveButton("Oui",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        MainActivity.this.finish();
                    }
                })

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

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

/*
    CREATE TABLE table_users (
    id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
    name VARCHAR(50) NOT NULL,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
    );
INSERT INTO table_users(name, username, password) VALUES('patrice', 'delpy', 'xyz');

*/