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.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
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 com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

public class emprunter_by_listview extends AppCompatActivity
{
    private ListView listviewitems;

    private Listview_selection_jeu adapter;

    private Button btn_scanner ,btn_delete_all, btn_emprunter, btn_retour;

    int cpt = 0;

    ArrayList<String> listItems;

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

    JSONParser jsonParser = new JSONParser();

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

    //    private static String url_check_jeu_disponible = "http://analog-design.net/WORKAREA/WEBSITE/reservation/check_jeu_disponible.php";
    private static String url_check_jeu_disponible = "http://analog-design.net/WORKAREA/WEBSITE/reservation/tartuffe.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";

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

    private String retour = null;

    private String barcode;

    public static final String key_nom_utilisateur = "nom_utilisateur";

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

    ArrayList<String> list_jeu_selection = new ArrayList<String>();

    String nom_uilisateur;

    boolean debug_mode = false;

    SharedPreferences sharedpreferences;

    SharedPreferences.Editor editor;
    /***********************************************/

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

        Intent intent = getIntent();
        String jeu = intent.getStringExtra("jeu");

        sharedpreferences = getSharedPreferences("debug_PREFERENCE", Context.MODE_PRIVATE);

        load_preferences(jeu);

        //   SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);

      //  SharedPreferences.Editor editor = sharedpreferences.edit();

        nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);

        listviewitems = (ListView) findViewById(R.id.lv_jeu);

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

        adapter = new Listview_selection_jeu(emprunter_by_listview.this, AppArrList);
        listviewitems.setAdapter(adapter);

        // pour sauver les datas de l'activity si une rotation de l'écran se produit: normalement ils est interdit dans manifest
        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_retour.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                finish();
                Intent i = new Intent(getApplicationContext(), listview_all_games_in_db_06.class);
                startActivity(i);

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

        btn_emprunter.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                /*if(debug_mode)
                {
                    debug_mode_enregistre_retrait();
                }
                else
                {
                    confirm_emprunter_dialog();
                }*/

                confirm_emprunter_dialog();
            }
        });

        getSupportActionBar().setTitle("  Panier " + nom_uilisateur);
        getSupportActionBar().setLogo(R.drawable.shopping_cart);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);


    }

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

    public void load_preferences(String jeu)
    {

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

        btn_delete_all =(Button) findViewById(R.id.btn_delete_all);
        btn_emprunter =(Button) findViewById(R.id.btn_emprunter);

        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        List <String> temp_list = new ArrayList<String>();

       // editor.clear();
       // editor.commit();

        boolean key_existe = sp.contains("size");

        if(key_existe)
        {
            int size = sp.getInt("size", 0);
            String val;

            for (int j = 0; j < size; j++)
            {
                int pos = j + 1;
                String index = "val" + Integer.toString(pos);

                val = sp.getString(index, null);
                HashMap<String, String> map;
                map = new HashMap<String, String>();
                map.put("nom", val);
                map.put("barcode", ""); // vide
                AppArrList.add(map);
                temp_list.add(val);
            }
        }
        /***********/

        if(jeu == null)
        {
            String ppp = "4";
        }


        else
        {
            boolean flag_existe = false;

            //Load the list into a hashSet
            Set<String> set = new HashSet<String>(temp_list);
            if (set.contains(jeu))
            {
                Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                flag_existe = true;
                btn_delete_all.setEnabled(true);
                btn_emprunter.setEnabled(true);
            }

            if (!flag_existe)
            {

                if (AppArrList.size() >= 5)
                {
                    dialog_depassement_retrait();
                    btn_delete_all.setEnabled(true);
                    btn_emprunter.setEnabled(true);
                }
                else
                {
                    // datas
                    HashMap<String, String> map;
                    map = new HashMap<String, String>();
                    map.put("nom", jeu);
                    map.put("barcode", ""); // vide
                    AppArrList.add(map);

                    // sauvegarde des preferences
                    int size = sp.getInt("size", 0);
                    size = size + 1;
                    String index = "val" + Integer.toString(size);

                    editor.putString(index, jeu);
                    editor.putInt("size", AppArrList.size());
                    editor.commit();
                    cpt = cpt + 1;
                }

                btn_delete_all.setEnabled(true);
                btn_emprunter.setEnabled(true);

            } else {
                /************* états des bouton par défault ******************/

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

                /*if (debug_mode)
                {
                    btn_emprunter.setEnabled(true);
                } else {
                    btn_emprunter.setEnabled(false);
                }*/
            }
        }
    }

    /*
        for(int i=0; i < AppArrList.size(); i++)
        {

            HashMap<String, String> hashmap = new HashMap<String, String>();
            hashmap = AppArrList.get(i);
            boolean flag = hashmap.containsKey(jeu);

            if(flag)
            {
                Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                flag_existe = true;
                break;
            }

        }
*/

    /***********************************************/
/*
    public void add_new_selection(String jeu)
    {
        SharedPreferences sp = getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        boolean flag_existe = false;

        for(int i=0; i < AppArrList.size(); i++)
        {

            HashMap<String, String> hashmap = new HashMap<String, String>();
            hashmap = AppArrList.get(i);
            boolean flag = hashmap.containsKey(jeu);

            if(flag)
            {
                Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                flag_existe = true;
                break;
            }

        }

        if(!flag_existe)
        {
                if(AppArrList.size() > 50)
                {
                    dialog_depassement_retrait();
                }

            else {
                    // datas
                    HashMap<String, String> map;
                    map = new HashMap<String, String>();
                    map.put("nom", jeu);
                    map.put("barcode", ""); // vide
                    AppArrList.add(map);

                    // sauvegarde des preferences
                    int size = sp.getInt("size", 0);
                    size = size + 1;
                    String index = "val" + Integer.toString(size);

                    editor.putString(index, jeu);
                    editor.putInt("size", AppArrList.size());
                    editor.commit();


/*  OK valide


                SharedPreferences sp = getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();

                list_jeu_selection.add("value1");
                list_jeu_selection.add("value2");
                list_jeu_selection.add("value3");
                list_jeu_selection.add("value4");
                list_jeu_selection.add("value5");
                list_jeu_selection.add("value6");

                editor.putInt("size",47);

                for(int i=0;i<list_jeu_selection.size();i++)
                {
                    String valeur = list_jeu_selection.get(i);

                    String index = "val" + Integer.toString(i);

                    editor.putString( index, valeur );
                }
                editor.putInt("size",list_jeu_selection.size());
                editor.commit();

                list_jeu_selection.clear();

                int size = sp.getInt("size",0);

                for(int j=0;j<size;j++)
                {
                    list_jeu_selection.add( sp.getString( "val"+j , null) );
                }
*/

                  //  adapter.notifyDataSetChanged();
/*
                    cpt = cpt + 1;
                    btn_delete_all.setEnabled(true);
                    btn_emprunter.setEnabled(true);
            }
        }

    }
*/

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

    private void dialog_depassement_retrait()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Attention !");
        builder.setMessage("Pas plus de 5 jeux emprunter simultanément !.");

        builder.setCancelable(false);

        builder.setNegativeButton("Close", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "Abandon", Toast.LENGTH_SHORT).show();
            }
        });

        builder.show();
    }

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

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

        final String jeu_selection =  AppArrList.get(position_item).get("nom");
        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)
                    {
                        AppArrList.remove(position_item); // supprime l'item qui est en selection

                        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();

                        editor.remove(jeu_selection); // will delete key name
                        editor.putInt("size", AppArrList.size()); // on fait -1 sur la taille
                        editor.commit();
                        cpt = cpt - 1;

                        adapter.notifyDataSetChanged();

                        int size = AppArrList.size();
                        if(size == 0)
                        {
                            editor.remove("size");
                            editor.commit();

                            cpt = 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();

    }

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

    protected void removeAllItemFromList()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(emprunter_by_listview.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();

                        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();

                        for (int j = 0; j < AppArrList.size(); j++)
                        {
                            int pos = j + 1;
                            String index = "val" + Integer.toString(pos);
                            String val = sp.getString(index, null);
                            editor.remove(val);
                        }

                        editor.remove("size");
                        editor.commit();

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

    }

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

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

        public Listview_selection_jeu(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;

        }

    }

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

    public void debug_mode_enregistre_retrait()
    {
        AppArrList.clear();
        HashMap<String, String> map;
        map = new HashMap<String, String>();
        map.put("nom", "Alexandros");
        map.put("barcode", "1234567890128");
        AppArrList.add(map);


        map = new HashMap<String, String>();
        map.put("nom", "Ahoy");
        map.put("barcode", "1234567890128");
        AppArrList.add(map);


        map = new HashMap<String, String>();
        map.put("nom", "Bali");
        map.put("barcode", "1234567890128");
        AppArrList.add(map);


        confirm_emprunter_dialog();
    }

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

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

        // message afficher dans la dialog box
        String concate = "";

        for (int i = 0; i < AppArrList.size() ; i++)
        {
            concate = concate + AppArrList.get(i).get("nom") + "\n";
        }

        builder.setMessage(concate);
        builder.setCancelable(false);

        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                new insert_emprunt_db().execute(nom_uilisateur);
            }
        });

        builder.setNegativeButton("Non", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "Abandon", Toast.LENGTH_SHORT).show();
            }
        });

        builder.show();
    }

    private void dialog(String msg)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Attention !");
        //builder.setMessage("Ce jeux n'ont pas été rendu ?");
        msg = msg.replace('+', '\n');

        msg = "Jeu(x) en mode emprunt, retrait impossible (consistant) " + "\n" + "\n" + msg;

        builder.setMessage(msg);
        builder.setCancelable(false);

        builder.setNegativeButton("Close", 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();
        }

        protected String doInBackground(String... args)
        {
            String nom_uilisateur = args[0];
            String concate_jeu = "";
            String concate_barcode = "not_used";
            String 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;
                concate_barcode = concate_barcode + AppArrList.get(i).get("barcode") + tag;
            }

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

            // soumettre  JSON Object en mode http
            JSONObject json = jsonParser.makeHttpRequest(url_inserer_emprunt_jeu, "POST", params);
            Log.v("***** Create Response", json.toString());

            String infos_traitement = "";

            // verifier la valeur du TAG de retour du serveur
            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)
        {

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

                // on vide le panier

                SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();

                for (int j = 0; j < AppArrList.size(); j++)
                {
                    int pos = j + 1;
                    String index = "val" + Integer.toString(pos);
                    String val = sp.getString(index, null);
                    editor.remove(val);
                }

                editor.remove("size");
                editor.commit();

                finish();

            }
            else
            {
                Toast.makeText(getApplicationContext(), "Probléme de traitement ou perte de réseau !.", Toast.LENGTH_LONG).show();
            }

        }
    }

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

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

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

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

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


    @Override
    public void onBackPressed()
    {
        finish();


      /*  Class parent = listview_all_games_in_db_06.class;

        Intent i = new Intent(this, parent);
        startActivity(i);
        //add extras to intent if needed
        this.finish();*/

    }

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

}

