package com.example.patrice.notification_message;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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 String url_add_token_db = "http://analog-design.net/WORKAREA/WEBSITE/douche/inscription_douche.php";


    private static final String TAG_SUCCESS = "success";
    JSONParser jsonParser = new JSONParser();

    // preferences
    SharedPreferences sharedpreferences;
    public static final String key_inscription_nom_utilisateur = "key_inscription_nom_utilisateur";

    Activity context = this;

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

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

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

        inputEmail = (EditText) findViewById(R.id.tv_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

                    int pos = email.indexOf(".");
                    if(pos < 0 ) // -1 donc n'existe pas
                    {
                        Toast.makeText(getApplicationContext(), "L'email ne contient pas le point de séparation !", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        String s1 = email.substring(0, email.indexOf("."));
                        String s2 = email.substring(email.indexOf(".") + 1);

                        String str_prenom = s1.substring(0, 1).toUpperCase() + s1.substring(1);
                        String str_nom = s2.substring(0, 1).toUpperCase() + s2.substring(1);

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

                        requete_verif_email(email);

                    }

                    // recherche la position du symbole
                    // pos = email.indexOf("@");
                    // String retour = email.substring(0,pos);
                    //  String domaine = "onsemi.com";
                    //   boolean existe = email.toLowerCase().contains(domaine.toLowerCase());

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


                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Veuillez saisir votre email ONsemi!", 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 requete_verif_email(final String email)
    {

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

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

            JSONObject json = jsonParser.makeHttpRequest(url_user_enregistrement, "POST", params);

            Log.v(" ****** Create account", 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("PREFERENCE", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(key_inscription_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"))
            {

                String token = SharedPrefManager.getInstance(creation_compte.this).getDeviceToken();

                new update_database().execute(token);

            }

        }

    }


    public class update_database extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args)
        {
            String token = args[0];
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("token", token));
            params.add(new BasicNameValuePair("user", utilisateur )); // il faut le nom du type Delpy  ou Foulon premiere lettre du nom en majuscule

            JSONObject json = jsonParser.makeHttpRequest(url_add_token_db, "POST", params);

            Log.d("Create Response", json.toString());

            String reponse = null;

            try
            {
                //int success = json.getInt(TAG_SUCCESS);
                String msg = json.getString("success");

                if (msg.equals("1")) {
                    reponse = "OK";
                } else {
                    reponse = "FAIL";
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return (reponse);

        }

        @Override
        protected void onPostExecute(String result)
        {
            if (result.equals("OK"))
            {
                Toast.makeText(getApplicationContext(), "Inscription réussie à l'appli pour la douche  :)", Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Erreur de traitement : Sauvegarde impossible !", Toast.LENGTH_LONG).show();
            }


            Intent intention = new Intent();
            setResult(1234,intention);
            finish();//finishing activity
            //finish();
            //finishActivity(0);

        }
    }

    @Override
    public void onBackPressed()
    {

        //Intent i = new Intent(getApplicationContext(), traitement_scanner03.class);
        //startActivity(i);

        //finish();
        //System.exit(0);

        creation_compte.this.finishAffinity();
        System.exit(0);

    }

}

