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.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

// https://androidjson.com/android-server-login-registration-php-mysql/

// https://androidjson.com/android-server-login-registration-php-mysql/

public class user_inscription extends Activity
{

    private static final String TAG = "MainActivity.java";

    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputPassword;
    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 String url_user_enregistrement = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/debug.php";


    private static final String TAG_SUCCESS = "success";

    JSONParser jsonParser = new JSONParser();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.enregistrement_layout);

        //inputFullName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        //inputPassword = (EditText) findViewById(R.id.password);
        btn_register = (Button) findViewById(R.id.btn_register);


        btn_register.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                //String name = inputFullName.getText().toString().trim();
                String email = inputEmail.getText().toString().trim();
                //String password = inputPassword.getText().toString().trim();

                //if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty())
                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);

                    ///// name.substring(0,1).toUpperCase() + name.substring(1);

                    //String str_prenom = token.nextToken().toUpperCase();
                    //String str_nom = token.nextToken().toUpperCase();

                    // PB ????
                    //String[] parts = split_first.split(".");
                    //String aaa = parts[0];
                    //String bbb = parts[1];


                    //String[] separated = split_first.split(".");
                    //String str_prenom = separated[0].toUpperCase();
                    //String str_nom = separated[1].toUpperCase();
                    email = str_prenom + "." + str_nom + "@onsemi.com";
                    //String phone = "7812010205";

                    String phone_number = getPhone(user_inscription.this);
                    Toast.makeText(getApplicationContext(), phone_number , Toast.LENGTH_LONG) .show();

                    //http://www.tutos-android.com/android-6-permissions

                    // https://www.android-examples.com/request-check-multiple-runtime-permissions-android-marshmallow/

                    //https://www.journaldev.com/10409/android-runtime-permissions-example

                    //TelephonyManager tMgr = (TelephonyManager)Context.getSystemService(TELEPHONY_SERVICE);
                    //String mPhoneNumber = tMgr.getLine1Number();
                    // Phone--> Settings --> About --> Phone Identity,

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



    }

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

    private String getIMEI(Context context)
    {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager == null)
        {
            return null;
        }

        return telephonyManager.getDeviceId();
    }

    private String getPhone(Context context)
    {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager == null)
        {
            return null;
        }

        return telephonyManager.getLine1Number();
    }

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

    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(user_inscription.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];

            //post(name, email);

            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";
                }
                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();
            }
        }

    }

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

    private void post(String name, String email)
    {
        try
        {
            String postReceiverUrl = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/user_enregistrement.php";
            Log.v("TAG" , "postURL: " + postReceiverUrl);

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("name", name ));
            nameValuePairs.add(new BasicNameValuePair("email", email ));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null)
            {
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v("TAG", "Response: " +  responseStr);

                // you can add an if statement here and do other actions based on the response
            }

        }

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

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

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

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

        protected void onPreExecute()
        {
            super.onPreExecute();
            // do stuff before posting data
        }

        @Override
        protected String doInBackground(String... strings)
        {
            try
            {
                // 1 = post text data, 2 = post file
                int actionChoice = 2;

                // post a text data
                if(actionChoice==1)
                {
                    postText();
                }

                // post a file
                else
                {
                    //postFile();
                }

            }

            catch (NullPointerException e)
            {
                e.printStackTrace();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String lenghtOfFile)
        {
            // do stuff after posting data
        }
    }

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

    // this will post our text data
    private void postText()
    {
        try
        {
            // url where the data will be posted
            String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("firstname", "Mike"));
            nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
            nameValuePairs.add(new BasicNameValuePair("email", "mike@testmail.com"));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

                if (resEntity != null)
                {
                    String responseStr = EntityUtils.toString(resEntity).trim();
                    Log.v(TAG, "Response: " +  responseStr);
                   // you can add an if statement here and do other actions based on the response
                }

        }

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

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

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

    /*
    // will post our text file
    private void postFile(){
        try{

            // the file to be posted
            String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
            Log.v(TAG, "textFile: " + textFile);

            // the URL where the file will be posted
            String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);

            // new HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            File file = new File(textFile);
            FileBody fileBody = new FileBody(file);

            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file", fileBody);
            httpPost.setEntity(reqEntity);

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {

                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);

                // you can add an if statement here and do other actions based on the response
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    */

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

}

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