package com.example.patrice.rerservation01;

import android.Manifest;
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.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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 int REQUEST_PERMISSION = 200;

    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;

    Activity context = this;

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

        setContentView(R.layout.enregistrement_layout);

        sharedPreference = new sharedPreference();
        sharedPreference.save(context, "key_nom", "text"); // attention text n'est pas une clé, plantage !!!

        sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
        if (sharedpreferences.contains(key_email))
        {
            Toast.makeText(getApplicationContext(), "*** Preferences ***", Toast.LENGTH_LONG).show();
        }

        String str_valeur = sharedPreference.getValue(context, "key_nom" ); // attention text n'est pas une clé, plantage !!!

        getPhoneInfos();

        //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 getPhoneInfos()
    {
        if (ContextCompat.checkSelfPermission(user_inscription.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(user_inscription.this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_PERMISSION);
        }

        TelephonyManager phone_Mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        String deviceid = phone_Mgr.getDeviceId(); // IMEI code
        String subscriberid = phone_Mgr.getSubscriberId();
        String phonenumber = phone_Mgr.getLine1Number();

        Toast.makeText(getApplicationContext(), "Infos: " + deviceid + " " + phonenumber, Toast.LENGTH_LONG).show();

        /*
                //Get the IMEI code
                String deviceid = tm.getDeviceId();
        //Get  the phone number string for line 1,For ex: the MSISDN for a GSM phone
                String phonenumber = tm.getLine1Number();
        //Get  the software version number for the device, For ex: the IMEI/SV for GSM phones
                String softwareversion = tm.getDeviceSoftwareVersion();
        //Get  the alphabetic name of current registered operator.
                String operatorname = tm.getNetworkOperatorName();
        //Get  the ISO country code equivalent for the SIM provider's country code.
                String simcountrycode = tm.getSimCountryIso();
        //Get  the Service Provider Name (SPN).
                String simoperator = tm.getSimOperatorName();
        //Get  the serial number of the SIM, if applicable. Return null if it is unavailable.
                String simserialno = tm.getSimSerialNumber();
        //Get  the unique subscriber ID, for example, the IMSI for a GSM phone
                String subscriberid = tm.getSubscriberId();
        //Get the type indicating the radio technology (network type)
        //currently in use on the device for data transmission.EDGE,GPRS,UMTS  etc
                String networktype = getNetworkTypeString(tm.getNetworkType());
        //This indicates the type of radio used to transmit voice calls
        //GSM,CDMA etc
                String phonetype = getPhoneTypeString(tm.getPhoneType());
         */

    }

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

    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";
                    // création shared preferences
                    save_preferences(email);
                }
                if (success == 2)
                {
                    infos_traitement = "Email inexistant, recommancer la saisie !";
                }
                if (success == 3)
                {
                    infos_traitement = "Mise à jour du smartphone !";
                    // mise à jour shared preferences
                    save_preferences(email);
                }
            }

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

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

    public void save_preferences(String email)   //(View view)
    {
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(key_email, email);
        editor.commit();
    }

/*
    public void clear(View view)
    {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        name.setText("");
        email.setText("");

    }

    public void Get(View view)
    {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }
    }
*/
    /******************************************/


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