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.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 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.List;
import java.util.concurrent.ExecutionException;

public class traitement_scanner03 extends Activity
{
    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>>();

    String nom_uilisateur;

    boolean debug_mode = true;

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

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

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

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

        // 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_scanner.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                IntentIntegrator integrator = new IntentIntegrator(traitement_scanner03.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();
                Intent i = new Intent(getApplicationContext(), Main02.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();
                }

            }
        });

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

        btn_delete_all.setEnabled(false);

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

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

    }

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

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

        super.onActivityResult(requestCode, resultCode, data);

        String game_name = "";

        // nouvel enregistrement
        if(requestCode == 250)
        {
            game_name = data.getStringExtra("TAG_NAME");
            //Toast.makeText(this, "+++++" + blabla, Toast.LENGTH_LONG).show();

            int size = AppArrList.size();
            int pos = size - 1;
            AppArrList.get(pos).put("nom", game_name);

            adapter.notifyDataSetChanged();
        }

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

            else
            {
                Log.v("******** Info: ", "Scanned");
                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;

                boolean flag_existe = false;

                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_existe = true;
                        break;
                    }
                }

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

                    if(AppArrList.size() > 5)
                    {
                        dialog_depassement_retrait();
                    }

                    else
                    {
                        HashMap<String, String> map;
                        map = new HashMap<String, String>();
                        map.put("nom", retour); // c'est le nom qui a été trouvé
                        map.put("barcode", barcode);
                        AppArrList.add(map);

                        //listItems.add(infos);
                        //adapteritem.notifyDataSetChanged();
                        adapter.notifyDataSetChanged();

                        cpt = cpt + 1;
                        btn_delete_all.setEnabled(true);
                        btn_emprunter.setEnabled(true);
                    }
                }


            }
        }

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

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

    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(traitement_scanner03.this);
        builder.setTitle("Alert!");

        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
                        adapter.notifyDataSetChanged();

                        int size = AppArrList.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();

    }

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

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

    }

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

    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'emprunt !");
        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)
            {

                try
                {
                    retour = new check_jeu_disponible().execute().get();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                catch (ExecutionException e)
                {
                    e.printStackTrace();
                }

                if( retour.length() == 0 )
                {
                    Toast.makeText(getApplicationContext(), "Continu", Toast.LENGTH_LONG).show();
                    //new insert_emprunt_db().execute(nom_uilisateur);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Stop", Toast.LENGTH_LONG).show();
                    dialog(retour);
                }


            }
        });

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

    /***********************************************/
    // verifier que le jeu n'est pas dàja en retrait car on ne peut pas prendre un jeu qui n'a pas été rendu !!! élémentaire mon cher

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

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

        protected String doInBackground(String... args)
        {
            String concate_jeu = "";
            String tag = "";
            String message = "";

            // construire les chaines envoyées au serveur , elles seront découpées pour récupérer les infos
            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("liste_jeu", concate_jeu));

            JSONObject json = jsonParser.makeHttpRequest(url_check_jeu_disponible, "POST", params);
            Log.v("***** Create Response", json.toString());

            JSONArray datas = null;

            try
            {

                int success = json.getInt(TAG_SUCCESS);

               message =  json.getString("message");
            }

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

            return message;
        }

        protected void onPostExecute(String s)
        {
        }
    }


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

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

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

        protected String doInBackground(String... args)
        {
            String nom_uilisateur = args[0];
            String concate_jeu = "";
            String concate_barcode = "";
            String tag = "";

            // construire les chaines envoyées au serveur , elles seront découpées pour récupérer les infos
            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)
        {
            pDialog.dismiss();

            if(infos_traitement.equals("OK") )
            {
                Toast.makeText(getApplicationContext(), "La réservation est validée :)", Toast.LENGTH_LONG).show();
            }
            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);
    }

    /***********************************************/
    // methode pour vérifier l'appairage
    public void check_database(String barcode)
    {
        try
        {
            retour = new check_db().execute(barcode).get();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        if (retour.equals("existe"))
        {
           // ne fait rien
        }
        else
        {
            // il faut demander au joueur de faire l'appairage
            Intent i;
            i = new Intent(getApplicationContext(), traitement_03.class);
            i.putExtra("barcode", barcode);
            startActivityForResult(i, 250);
        }
    }

    /***********************************************/
    // verifier que le barcode est present dans la table appli_table_jeu, donc que le nom du jeu est sont code barre sont appairé
    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;

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

    /***********************************************/
    // retourne le nom du jeu associe au barcode
    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;

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

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

    @Override
    public void onBackPressed()
    {
        Intent i = new Intent(getApplicationContext(), Main02.class);
        startActivity(i);
    }

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

}
