package com.example.patrice.rerservation01;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
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;

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

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

        //BackgroundWorker backgroundWorker = new BackgroundWorker(this);
        //backgroundWorker.execute(username, password);

        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, "Item1...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), Query_all.class);
                startActivity(i);
                break;
            case R.id.item2:
                Toast.makeText(this, "Item2... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), scanner_barcode06.class);
                startActivity(i);
                break;
            case R.id.item3:
                Toast.makeText(this, "Item3... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), mes_emprunts.class);
                startActivity(i);
                break;
            case R.id.item4:
                Toast.makeText(this, "Item4...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), mes_emprunts04.class);
                startActivity(i);
                break;
            case R.id.item5:
                Toast.makeText(this, "Item5...", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), listview001.class);
                startActivity(i);
                break;
            case R.id.item6:
                Toast.makeText(this, "Item6...", Toast.LENGTH_LONG).show();
                break;
            case R.id.item7:
                Toast.makeText(this, "Item7...", Toast.LENGTH_LONG).show();
                break;
            case R.id.item8:
                Toast.makeText(this, "Item8...", Toast.LENGTH_LONG).show();
                break;
            case R.id.item9:
                Toast.makeText(this, "Salut...", Toast.LENGTH_LONG).show();
                quitter_confirmation();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

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

*/