package com.example.patrice.rerservation01;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
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;

//http://codeofandroid.blogspot.fr/2016/02/listview-delete-item-delete-row-item-in.html

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

    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;

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


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

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

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

        listItems = new ArrayList<String>();

        final Activity activity = this;


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

        btn_scanner.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //listItems.add("plouf "+ cpt);
                //adapteritem.notifyDataSetChanged();
                //cpt = cpt + 1;
                //btn_delete_all.setEnabled(true);
                //btn_emprunter.setEnabled(true);

//                Intent i = new Intent(getApplicationContext(), database_jeu.class);
//                startActivityForResult( i, MY_REQUEST_CODE );
                //startActivity(i);

                /***********************/
                IntentIntegrator integrator = new IntentIntegrator(activity);
                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.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();
            }
        });

/*
        listviewitems.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View view,  int position, long id)
            {
                String value = listviewitems.getItemAtPosition(position).toString();
                int pos = Integer.parseInt(value);
                removeItemFromList(pos);

//                String msg = ((TextView) view).getText() + " " + value;
//                Toast.makeText(getApplicationContext(),  ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
//                Toast.makeText(getApplicationContext(),  msg , Toast.LENGTH_SHORT).show();
//                listItems.remove( listviewitems.getItemAtPosition(position) );
//                adapter.notifyDataSetChanged();

            }
        });


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

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

        //adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
        //listviewitems.setAdapter(adapter);

        adapteritem = new totoAdapter(scanner_barcode07.this, listItems);
        listviewitems.setAdapter(adapteritem);
    }


/*
    protected void onActivityResult( int requestCode, int resultCode,  Intent pData)
    {
        if ( requestCode == MY_REQUEST_CODE )
        {
            if (resultCode == Activity.RESULT_OK )
            {

                final String selection_jeu = pData.getExtras().getString( database_jeu.EXTRA_STRING_NAME );

                if(listItems.contains( selection_jeu ) )
                {
                    //item is existing in the list
                    Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    listItems.add(selection_jeu);
                    adapteritem.notifyDataSetChanged();
                    cpt = cpt + 1;
                    btn_delete_all.setEnabled(true);
                    btn_emprunter.setEnabled(true);
                }

                //Toast.makeText(getApplicationContext(),  zData , Toast.LENGTH_SHORT).show();
                //..do something with our retrieved value..

                //Log.v( TAG, "Retrieved Value zData is "+zData );
                //..logcats "Retrieved Value zData is returnValueAsString"

            }
        }

    }
*/

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

                final String selection_jeu = data.getExtras().getString( database_jeu.EXTRA_STRING_NAME );

                if(listItems.contains( selection_jeu ) )
                {
                    //item is existing in the list
                    Toast.makeText(getApplicationContext(), "Existe dans la selection !.", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    listItems.add(selection_jeu);
                    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(scanner_barcode07.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) );
                        adapteritem.notifyDataSetChanged();
                        Toast.makeText(getApplicationContext(),  "Poubelle", 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();

    }

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

    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 = "";

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

        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(scanner_barcode07.this);
            pDialog.setMessage("Ajouter la réservation..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

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

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

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

            }

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("client", name));
            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();
            }

        }

    }

}
