package com.example.patrice.rerservation01;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

public class creation_compte extends AppCompatActivity
{
    private EditText inputEmail;
    private Button btn_register;
    private ProgressDialog pDialog;

    private static String url_user_enregistrement = "http://analog-design.net/WORKAREA/WEBSITE/reservation/validation_client.php";
    private static final String TAG_SUCCESS = "success";
    JSONParser jsonParser = new JSONParser();

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

    Activity context = this;

    String email = "";
    String utilisateur = "";

    // user_inscription  a voir

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

/*      OK
        sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(key_nom, "nada");

        editor.commit();

        String return_val = sharedpreferences.getString(key_nom, "");
*/

        ActionBar actionBar = getSupportActionBar(); // or getActionBar();
        getSupportActionBar().setTitle("Enregristrement"); // 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);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        inputEmail = (EditText) findViewById(R.id.email);
        btn_register = (Button) findViewById(R.id.btn_register);

        btn_register.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                email = inputEmail.getText().toString().trim();

                if (!email.isEmpty())
                {
                    // mise en forme de l'adresse email
                    // Prenom.Nom@onsemi.com
                    String split_first = email.substring(0, email.indexOf("@"));
                    String split_second = email.substring(email.indexOf("@") + 1);

                    StringTokenizer token = new StringTokenizer(split_first, ".");

                    String str_prenom = token.nextToken();
                    str_prenom = str_prenom.substring(0, 1).toUpperCase() + str_prenom.substring(1);
                    String str_nom = token.nextToken();
                    str_nom = str_nom.substring(0, 1).toUpperCase() + str_nom.substring(1);

                    // reconstitution
                    email = str_prenom + "." + str_nom + "@onsemi.com";
                    utilisateur = str_nom;

                    confirm_emprunter_dialog(email);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Please enter your details!", Toast.LENGTH_LONG).show();
                }
            }
        });


    }

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

    // pour le retour - inclus dans l'action bar ( < )
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

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

    private void confirm_emprunter_dialog(final String email)
    {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirmation de votre Email !");

       // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
       // String currentDateandTime = sdf.format(new Date());

        builder.setMessage(email);

        builder.setCancelable(false);

        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new user_enregistrement_db().execute(email); // passage des paramétres ...
            }
        });

        builder.setNegativeButton("Non", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), "Abandon", Toast.LENGTH_SHORT).show();
            }
        });

        builder.show();
    }

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

    class user_enregistrement_db extends AsyncTask<String, String, String>
    {

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(creation_compte.this);
            pDialog.setMessage("Enregistrement ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args)
        {
            String email = args[0];

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email", email));

            // getting JSON Object
            JSONObject json = jsonParser.makeHttpRequest(url_user_enregistrement, "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            String infos_traitement = "";

            try
            {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 0)
                {
                    infos_traitement = "ERREUR";
                }

                if (success == 1)
                {
                    infos_traitement = "UNKNOWN";
                }

                if (success == 2)
                {
                    infos_traitement = "OK";
                    //sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);

                    sharedpreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(key_nom_utilisateur, utilisateur);
                    editor.putBoolean("isFirstRun", false); // pour le bypass
                    editor.commit();
                }

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

            return infos_traitement;
        }

        protected void onPostExecute(String infos_traitement)
        {
            pDialog.dismiss();

            if (infos_traitement.equals("ERREUR"))
            {
                Toast.makeText(getApplicationContext(), "Probléme réseau !.", Toast.LENGTH_LONG).show();
            }

            if (infos_traitement.equals("UNKNOWN"))
            {
                Toast.makeText(getApplicationContext(), "Utilisateur non reconnu, essayer encore une fois !", Toast.LENGTH_LONG).show();
            }

            if (infos_traitement.equals("OK"))
            {
                Toast.makeText(getApplicationContext(), "Inscription réussie au club LUDO , à vous de jouez ! :)", Toast.LENGTH_LONG).show();
                finish();
            }

        }

    }

}

/*
    create table users(
        id int(11) primary key auto_increment,
    unique_id varchar(23) not null unique,
        name varchar(50) not null,
        email varchar(100) not null unique,
        encrypted_password varchar(80) not null,
        created_at datetime,
        updated_at datetime null
        );
*/
