package com.example.patrice.rerservation01;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class traitement_scanner02 extends Activity
{
    private ListView listviewitems;
    private totoAdapter adapteritem;

    private ImageAdapter adapter;

    private Button btn_scanner ,btn_delete_all, btn_emprunter, btn_retour;

    int cpt = 0;

    ArrayList<String> listItems;

    public static final int MY_REQUEST_CODE = 123;

    int TAG_ENREGISTRE = 2000;

    private static final String STATE_LIST = "State Adapter Data";

    /* accés DB */
    JSONParser jsonParser = new JSONParser();
    //private static String url_inserer_emprunt_jeu = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/inserer_emprunt_jeu.php";
    private static String url_inserer_emprunt_jeu = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/inserer_retrait_jeu.php";

    private static String url_interroge_DB_jeu = "http://analog-design.net/WORKAREA/WEBSITE/reservation/interroge_jeu_DB_mysql.php";


    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private ProgressDialog pDialog;

    OrientationEventListener myOrientationEventListener ;

    //
//    private static String url_check_db =  "http://analog-design.net/WORKAREA/WEBSITE/reservation/check_db__request.php";
    private static String url_check_db =  "http://analog-design.net/WORKAREA/WEBSITE/reservation/barcode_request.php";

    private static String url_request_nom_game_name = "http://analog-design.net/WORKAREA/WEBSITE/reservation/request_jeu.php";

    private String retour = null;

    private String barcode;

    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String GAME_NAME = "game_name";


    SharedPreferences sharedpreferences;

    ArrayList<HashMap<String, String>> AppArrList = new ArrayList<HashMap<String, String>>();

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

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        listviewitems = (ListView) findViewById(R.id.lv_jeu);
        btn_scanner =(Button) findViewById(R.id.btn_scanner);
        btn_retour =(Button) findViewById(R.id.btn_retour);
        btn_delete_all =(Button) findViewById(R.id.btn_delete_all);
        btn_emprunter =(Button) findViewById(R.id.btn_emprunter);

/*      désactivation le 22 / 03 /2018

        myOrientationEventListener = new OrientationEventListener(this,    SensorManager.SENSOR_DELAY_NORMAL)
        {
            @Override
            public void onOrientationChanged(int orientation)
            {
                if(listItems.size() != 0)
                {
                    btn_delete_all.setEnabled(true);
                    btn_emprunter.setEnabled(true);
                }
                else
                {
                    btn_delete_all.setEnabled(false);
                    btn_emprunter.setEnabled(false);
                }
            }
        };

        myOrientationEventListener.enable();
*/


        if (savedInstanceState != null)
        {
            listItems = (ArrayList<String>) savedInstanceState.getSerializable(STATE_LIST);
        }
        else
        {
            String[] items={}; // ?????
            listItems = new ArrayList<String>(Arrays.asList(items));

        }

        /************* Listener capture les événements ******************/

        btn_scanner.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                IntentIntegrator integrator = new IntentIntegrator(traitement_scanner02.this);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setOrientationLocked(true);
                integrator.setPrompt("Scan le code bar de la boîte de jeu");
                integrator.setCameraId(0);
                integrator.setBeepEnabled(false);
                //     integrator.setBarcodeImageEnabled(false);
                integrator.initiateScan();

            }
        });

        btn_retour.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                finish();
            }
        });

        btn_delete_all.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                removeAllItemFromList();
            }
        });

        btn_emprunter.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                confirm_emprunter_dialog();
                //Toast.makeText(getApplicationContext(),  "Réservation ..." , Toast.LENGTH_SHORT).show();
            }
        });

        /************* états des bouton par défault ******************/

        btn_delete_all.setEnabled(false);
        btn_emprunter.setEnabled(false);


      //  adapteritem = new totoAdapter(traitement_scanner02.this, listItems);
      //  listviewitems.setAdapter(adapteritem);


        adapter = new ImageAdapter(traitement_scanner02.this, AppArrList);
        listviewitems.setAdapter(adapter);


//  OK       listviewitems.setAdapter(new ImageAdapter(this,AppArrList));
//  OK      final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

    }


    /******************************************/
/*
    protected void onActivityResult( int requestCode, int resultCode,  Intent data)
    {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if(result != null)
        {

            if (result.getContents() == null)
            {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Pas de scan !.", Toast.LENGTH_LONG).show();
            }

            else
            {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                barcode = result.getContents();

                check_database(barcode);

                try
                {
                    retour = new request_game_name().execute(barcode).get();
                }

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

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

                String infos = retour + " " + barcode;

/*
                if (listItems.contains(infos)) // barcode
                {
                    //item is existing in the list
                    Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                }
*/
/*
                boolean flag = true;

                for(HashMap hm:AppArrList)
                {
                    String existe_val = hm.get("nom").toString();

                    if (existe_val.equals(retour)) // correspond au nom du jeu
                    {
                        Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                        flag = false;
                        break;
                    }
                }

                if(flag)
                {
                        HashMap<String, String> map;

                        map = new HashMap<String, String>();
                        map.put("nom", retour); // c'est le nom
                        map.put("barcode", barcode);
                        AppArrList.add(map);

                        //listItems.add(infos);
                        //adapteritem.notifyDataSetChanged();
                        cpt = cpt + 1;
                        btn_delete_all.setEnabled(true);
                        btn_emprunter.setEnabled(true);
                }

            }
        }

        else
        {
            super.onActivityResult(requestCode, resultCode, data);
        }

    }
*/

    /***********************************************/
    protected void onActivityResult( int requestCode, int resultCode,  Intent data)
    {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);


        if(result != null)
        {

            if (result.getContents() == null)
            {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Pas de scan !.", Toast.LENGTH_LONG).show();
            }

            else
            {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned plouf : " + result.getContents(), Toast.LENGTH_LONG).show();
                barcode = result.getContents();

                check_database(barcode);

                try
                {
                    retour = new request_game_name().execute(barcode).get();
                }

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

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

                String infos = retour + " " + barcode;

                if (listItems.contains(infos)) // barcode
                {
                    //item is existing in the list
                    Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    HashMap<String, String> map;

                    Toast.makeText(this, "********* : " + retour , Toast.LENGTH_LONG).show();

                    map = new HashMap<String, String>();
                    map.put("nom", retour); // c'est le nom
                    map.put("barcode", barcode);
                    AppArrList.add(map);

                    //listItems.add(infos);
                    //adapteritem.notifyDataSetChanged();
                    cpt = cpt + 1;
                    btn_delete_all.setEnabled(true);
                    btn_emprunter.setEnabled(true);

                }
            }
        }

        else
        {
            super.onActivityResult(requestCode, resultCode, data);
        }

    }


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

    protected void removeItemFromList(final int position_item)
    {
        /*
        AlertDialog.Builder builder = new AlertDialog.Builder(traitement_scanner02.this);
        builder.setTitle("Alert!");

        String jeu_selection = listItems.get(position_item);

        String msg = "Voulez-vous supprimer " + jeu_selection + " de la selection ?";

        builder.setMessage(msg)
                .setCancelable(false)

                .setPositiveButton("Oui", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {

                        //listItems.remove( listviewitems.getItemAtPosition(position_item) );
                       // AppArrList.remove(listviewitems.getItemAtPosition(position_item));
                       // adapter.notifyDataSetChanged();

                        //listItems.remove( listviewitems.getItemAtPosition(position_item) );
                        //adapteritem.notifyDataSetChanged();

                        Toast.makeText(getApplicationContext(),  "Trash debug one element !", Toast.LENGTH_SHORT).show();

                        int size = listItems.size();

                        if(size == 0)
                        {
                            btn_delete_all.setEnabled(false);
                            btn_emprunter.setEnabled(false);
                        }

                    }
                })

                .setNegativeButton("Non",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        dialog.cancel();
                    }
                });

        AlertDialog  alertDialog = builder.create();
        alertDialog.show();
*/

        String zozo = "null";

        int aa = (int) listviewitems.getItemAtPosition(position_item);

        String s = Integer.toString(aa);

        Toast.makeText(getApplicationContext(),  s + " +++++++++Trash debug one element !", Toast.LENGTH_SHORT).show();

        //listItems.remove( listviewitems.getItemAtPosition(position_item) );
       //  AppArrList.remove(listviewitems.getItemAtPosition(position_item));

        AppArrList.remove(position_item);


        adapter.notifyDataSetChanged();

        int a = 5;
        a = a + 5;
        a = a * a;

    }

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

    protected void removeAllItemFromList()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(traitement_scanner02.this);
        builder.setTitle("Alert!");

        String msg = "Voulez-vous supprimer toute la selection ?";

        builder.setMessage(msg)
                .setCancelable(false)

                .setPositiveButton("Oui", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        //listItems.clear();
                        AppArrList.clear();
                        adapter.notifyDataSetChanged(); //crach !!!
                        //adapteritem.notifyDataSetChanged();
                        cpt = 0;
                        Toast.makeText(getApplicationContext(),  "Poubelle", Toast.LENGTH_SHORT).show();
                        btn_delete_all.setEnabled(false);
                        btn_emprunter.setEnabled(false);
                    }
                })

                .setNegativeButton("Non",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        dialog.cancel();
                    }
                });

        AlertDialog  alertDialog = builder.create();
        alertDialog.show();

    }

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

    class totoAdapter extends BaseAdapter
    {
        private Context context; //context
        private ArrayList<String> items; //data source of the list adapter
        private LayoutInflater lyt_Inflater = null;

        //public constructor
        public totoAdapter(Context context, ArrayList<String> items)
        {
            this.context = context;
            this.items = items;
        }

        @Override
        public int getCount() {
            return items.size(); //returns total of items in the list
        }

        @Override
        public Object getItem(int position) {
            return items.get(position); //returns list item at the specified position
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent)
        {

            String Name = listItems.get(position);

            View view_lyt = convertView;

            lyt_Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view_lyt = lyt_Inflater.inflate(R.layout.scanner_barcode06_item_layout, null);

            TextView txtnm=(TextView) view_lyt.findViewById(R.id.txtTitle);
            ImageButton imgbtnDelete=(ImageButton) view_lyt.findViewById(R.id.imgbtnDelete);

            txtnm.setText(Name);

            imgbtnDelete.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    removeItemFromList(position);

                }
            });

            return view_lyt;
        }
    }

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

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list)
        {
            context = c;
            MyArr = list;
        }

        public int getCount()
        {
            return MyArr.size();
        }

        public Object getItem(int position)
        {
            return position;
        }

        public long getItemId(int position)
        {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent)
        {

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (convertView == null)
            {
                convertView = inflater.inflate(R.layout.pipo02, null);
            }


            TextView txtPosition = (TextView) convertView.findViewById(R.id.tv_infos01);
            txtPosition.setText("Jeu : " + MyArr.get(position).get("nom"));

            TextView txtPicName = (TextView) convertView.findViewById(R.id.tv_infos02);
            txtPicName.setText("Barcode : " + MyArr.get(position).get("barcode"));

            ImageButton imgbtnDelete=(ImageButton) convertView.findViewById(R.id.xxximgbtnDelete);

            imgbtnDelete.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    removeItemFromList(position);
                    //Toast.makeText(getApplicationContext(),  "Trash ", Toast.LENGTH_SHORT).show();

                }
            });

            return convertView;

        }

    }


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

    private void confirm_emprunter_dialog()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirmation de l'emprunt !");
        //builder.setMessage("Voulez-vous vraiment emprunter les jeux suivants ?");

        //int size = listItems.size();

        String concate = "";

/*       précédente version
        for (int i = 0; i < listItems.size() ; i++)
        {
            concate = concate + listItems.get(i) + "\n";
        }
*/
        for (int i = 0; i < AppArrList.size() ; i++)
        {
            concate = concate + AppArrList.get(i).get("nom") + "\n";
        }

        //AppArrList.get(i).get("nom")

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

        builder.setMessage(concate);

        builder.setCancelable(false);

        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                int nb_jeux = listItems.size();
                String str_nb_jeu = Integer.toString(nb_jeux);
                String msg;

                if(nb_jeux == 1)
                {
                    msg = "La réservation du jeu est validée";
                }
                else
                {
                    msg = "La réservation des " + str_nb_jeu + " jeux est validée";
                }

                //Toast.makeText(getApplicationContext(), "La réservation est validée", Toast.LENGTH_LONG).show();
                //Toast.makeText(getApplicationContext(), msg , Toast.LENGTH_LONG).show();

                new insert_emprunt_db().execute();

            }
        });

        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 insert_emprunt_db extends AsyncTask<String, String, String>
    {

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(traitement_scanner02.this);
            pDialog.setMessage("Ajouter la réservation..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args)
        {
            String client = "patoche";

            String concate_jeu = "";
            String tag = "";

/*          premiére version
            for (int i = 0; i < listItems.size() ; i++)
            {
                if(i != listItems.size() -1 )
                {
                    tag = "*";
                }
                else
                {
                    tag = "";
                }
                concate_jeu = concate_jeu + listItems.get(i) + tag;
            }
*/

            for (int i = 0; i < AppArrList.size() ; i++)
            {
                if(i != AppArrList.size() -1 )
                {
                    tag = "*";
                }
                else
                {
                    tag = "";
                }
                concate_jeu = concate_jeu + AppArrList.get(i).get("nom") + tag;
            }


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

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

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

            String infos_traitement = "";

            // check for success tag
            try
            {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1)
                {
                    infos_traitement = "OK";
                }
                else
                {
                    // failed
                    infos_traitement = "ERREUR";
                }
            }

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

            return infos_traitement;
        }

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

            //infos_traitement = "Transaction mysql OK";
            //infos_traitement = "Transaction avortée : erreur";

            if(infos_traitement.equals("OK") )
            {
                Toast.makeText(getApplicationContext(), "La réservation est validée :)", Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Probléme réseau !.", Toast.LENGTH_LONG).show();
            }

        }

    }

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

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putSerializable(STATE_LIST, listItems);
    }

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


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

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

        /**
         * background thread
         * */
        protected String doInBackground(String... args)
        {

            int success;
            String id = args[0];
            String reponse = null;

            try
            {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", id));
                JSONObject json = jsonParser.makeHttpRequest(url_interroge_DB_jeu, "GET", params);

                Log.d("Single Product Details", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);

                if (success == 1)
                {
                    if (success == 1)
                    {
                        //Toast.makeText(gestion_DB02.this, "Ajout réussi. ", Toast.LENGTH_LONG).show();
                        reponse = "OK";
                    }

                    else
                    {
                        // fail
                        // Toast.makeText(gestion_DB02.this, "Erreur pendant l'enregistrement !.", Toast.LENGTH_LONG).show();
                        reponse = "FAIL";
                    }

                }
            }

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

            return  reponse; //null;



        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }

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

    public void check_database(String barcode)
    {
        try
        {
            //String game_name  = "Ahoy";             // remplie
            //String game_name  = "Alexandros";     // vide
            retour = new check_db().execute(barcode).get();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        if (retour.equals("existe"))
        {
            // Toast.makeText(getApplicationContext(), " continu ", Toast.LENGTH_LONG).show();
            // retour à l'activity qui liste les jeu que l'on souhaite emprunter
        }
        else
        {
            //Toast.makeText(getApplicationContext(), "Aide utilisateur", Toast.LENGTH_LONG).show();
            Intent i;
            i = new Intent(getApplicationContext(), traitement_02.class);   // avant traitement
            i.putExtra("barcode", barcode);
            startActivity(i);
            //startActivityForResult(i, TAG_ENREGISTRE );
        }

    }


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

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

        protected String doInBackground(String... args)
        {

            String barcode = args[0];

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

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

            String reponse = null;

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

                if (success == 1)
                {
                    reponse = "existe";
                }

                else
                {
                    reponse = "vide";
                }
            }

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

            return reponse;
        }


        protected void onPostExecute()
        {
        }
    }


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

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

        protected String doInBackground(String... args)
        {

            String barcode = args[0];

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

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

            String reponse = null;

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

                if (success == 1)
                {
                    reponse = nom; // + "+" + "existe";
                }

                else
                {
                    reponse = "vide";
                }
            }

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

            return reponse;
        }


        protected void onPostExecute()
        {
        }
    }

}
