package com.example.patrice.reservation02;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class selection_jeu_in_listview extends AppCompatActivity
{

    private ListView lv;
    ArrayAdapter<String> adapter;
    EditText inputSearch;
    String retour;

    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> jeux_liste;

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

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "nom";

    JSONArray jeux = null;
    String products[];

    Button btn_abandon;
    Button btn_selection;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selection_jeu_in_listview_layout); //activity_main

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

        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);

        /*
        String computers[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
                "iPhone 4S", "Samsung Galaxy Note 800",
                "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
        */

        new charge_liste_jeux_db().execute();

        // Adding items to listview
        //adapter = new ArrayAdapter<String>(this, R.layout.search_list_item_layout, R.id.product_name, computers);
        //lv.setAdapter(adapter);


        lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();
                TextView val = (TextView) view.findViewById(R.id.product_name);
                Toast.makeText(getApplicationContext(), "selected Item Name is "+ val.getText(), Toast.LENGTH_LONG).show();
                inputSearch.setText(val.getText());
            }
        });

        inputSearch.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
            {
                // When user changed the Text
                selection_jeu_in_listview.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
            {
            }

            @Override
            public void afterTextChanged(Editable arg0)
            {
            }
        });

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

        btn_abandon =(Button) findViewById(R.id.btn_abandon);
        btn_abandon.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Toast.makeText(selection_jeu_in_listview.this, "Abandon" , Toast.LENGTH_LONG).show();
                finish();
            }
        });

        btn_selection =(Button) findViewById(R.id.btn_selection);
        btn_selection.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String input = inputSearch.getText().toString();
                confirme_dialog(input);
/*
 //               if(retour.equals("OK"))
                {
                    Intent intent=new Intent();
                    intent.putExtra("TAG_NAME", input );
                    setResult(150,intent);
                    finish();
                    Toast.makeText(MainActivity.this,"Retour à l'activité principale...",Toast.LENGTH_LONG).show();
                }
*/
                // Toast.makeText(MainActivity.this, input , Toast.LENGTH_LONG).show();


            }
        });





    }

    class charge_liste_jeux_db extends AsyncTask<String, String, String[]>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        protected String[] doInBackground(String... args)
        {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject json = jParser.makeHttpRequest(url_liste_jeux_db, "GET", params);

            Log.d("Tous les jeux: ", json.toString());

            String elements [] = null;

            try
            {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1)
                {
                    jeux = json.getJSONArray(TAG_PRODUCTS);

                    for (int i = 0; i < jeux.length(); i++)
                    {
                        JSONObject c = jeux.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);

                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        jeux_liste.add(map);

                    }
                }
                else
                {
                    // vide , ce n'est pas prévu
                }
            }

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


            return null;
        }

        protected void onPostExecute(String tab [])
        {
            /*
            String computers[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
                    "iPhone 4S", "Samsung Galaxy Note 800",
                    "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
            */

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

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

                HashMap<String, String> hashmap= jeux_liste.get(i);
                String nom = hashmap.get("nom");
                liste.add(nom);

            }

            // convertir arraylist en array
            String[] computers = liste.toArray(new String[liste.size()]);

            adapter = new ArrayAdapter<String>(selection_jeu_in_listview.this, R.layout.selection_jeu_in_listview_row_layout, R.id.product_name, computers);
            lv.setAdapter(adapter);

            Toast.makeText(selection_jeu_in_listview.this, "Patoche BINGO" , Toast.LENGTH_LONG).show();
        }
    }

    private void confirme_dialog(String input)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirmation du nom de jeu !.");
        builder.setMessage(input);
        builder.setCancelable(false);

        final String pipo = input;

        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //Toast.makeText(getApplicationContext(), "Selection", Toast.LENGTH_LONG).show();
                retour = "OK";
                Intent intent=new Intent();
                intent.putExtra("TAG_NAME", pipo );
                setResult(150,intent);
                finish();
                // Toast.makeText(MainActivity.this,"Retour à l'activité principale...",Toast.LENGTH_LONG).show();

            }
        });

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

        builder.show();


    }

}