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.util.Log;
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 Activity
{
    private EditText inputEmail;
    private Button btn_register;
    private ProgressDialog pDialog;

    private static String url_user_enregistrement = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/user_enregistrement.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 = "nom";
    public static final String key_email = "email";
    private sharedPreference sharedPreference;
    public static final String key_account = "key_account";
    Activity context = this;




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

        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)
            {
                String 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";
                    String phone = "7812010205";

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


    }

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

    private void confirm_emprunter_dialog(final String email, final String phone)
    {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirmation de l'emprunt !");

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

        builder.setMessage("Blabla ...");

        builder.setCancelable(false);

        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new user_enregistrement_db().execute(email, phone); // 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];
            String phone = args[1];

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

            // 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)
                {
                    // failed
                    infos_traitement = "ERREUR";
                }
                if (success == 1)
                {
                    infos_traitement = "OK";
                    sharedPreference = new sharedPreference();
                    sharedPreference.save(context, "key_account", email);
                }
                if (success == 2)
                {
                    infos_traitement = "Email inexistant, recommancer la saisie !";
                }
                if (success == 3)
                {
                    infos_traitement = "Mise à jour du smartphone !";
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }

            return infos_traitement;
        }

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

            if (infos_traitement.equals("OK")) {
                Toast.makeText(getApplicationContext(), "Inscription réussie , à vous de jouez ! :)", Toast.LENGTH_LONG).show();
            }
            if (infos_traitement.equals("Existe dans la DB ?")) {
                Toast.makeText(getApplicationContext(), "Existe dans la DB ? Recommencer", Toast.LENGTH_LONG).show();
            }
            if (infos_traitement.equals("ERREUR")) {
                Toast.makeText(getApplicationContext(), "Probléme réseau !.", Toast.LENGTH_LONG).show();
            }

            if (infos_traitement.equals("Mise à jour du smartphone !")) {
                Toast.makeText(getApplicationContext(), "Smartphone updated parameters", Toast.LENGTH_LONG).show();
            }
        }

    }

}

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