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.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

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.SearchView;
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 appairage_statut extends AppCompatActivity implements SearchView.OnQueryTextListener
{
    ListView listView;
    EditText inputSearch;
    Button btn_abandon;
    Button btn_selection;
    SearchView search_view;

    private static String url_liste_jeux_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/test_db.php";
    private static String url_appairage_requete_liste_jeux_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/appairage_request_all_games.php";
    int request_saisir_nom = 125;
    JSONArray element = null;
    Appairage_Adapter adapter;
    ArrayList<Listview_games> objet_list;
    String listview_selection;
    int appairage_count = 0;

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

        listView = (ListView) findViewById(R.id.list_view);
        search_view = (SearchView) findViewById(R.id.search_view);

        try
        {
            new ProcessJSON().execute(url_appairage_requete_liste_jeux_db).get();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        int nb_jeu = objet_list.size();

        getSupportActionBar().setTitle("   Jeux : " + appairage_count + " appairages sur " + nb_jeu  );
        getSupportActionBar().setLogo(R.drawable.books);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

        adapter = new Appairage_Adapter(getApplicationContext(), objet_list);
        listView.setAdapter(adapter);

        search_view.setOnQueryTextListener(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                TextView val = (TextView) view.findViewById(R.id.value);
                listview_selection = val.getText().toString();
                search_view.setQuery(listview_selection, false);
            }
        });

        btn_abandon =(Button) findViewById(R.id.btn_abandon);
        btn_abandon.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Toast.makeText(appairage_statut.this, "Abandon" , Toast.LENGTH_LONG).show();
                Intent intent=new Intent();
                intent.putExtra("TAG_NAME", "abandon" );
                setResult(request_saisir_nom,intent);
                finish();
            }
        });

        btn_selection =(Button) findViewById(R.id.btn_selection);
        btn_selection.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String input = search_view.getQuery().toString();
                Intent intent=new Intent();
                intent.putExtra("TAG_NAME", input );
                setResult(150,intent);
                finish();
                //confirme_dialog(input);
            }
        });
    }

    public boolean onQueryTextChange(String newText)
    {
        adapter.getFilter().filter(newText);
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query)
    {
        return false;
    }


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

    private class ProcessJSON extends AsyncTask<String, Void, String>
    {
        @Override
        protected void onPreExecute()
        {
        }

        @Override
        protected String doInBackground(String... strings)
        {
            String stream = null;
            String urlString = strings[0];
            newHTTPDataHandler hh = new newHTTPDataHandler();
            stream = hh.GetHTTPData(urlString);

            try
            {
                JSONObject jObj = null;
                jObj = new JSONObject(stream);
                element = jObj.getJSONArray("liste_jeux_db");
                objet_list = new ArrayList<Listview_games>();
                for (int i = 0; i < element.length(); i++)
                {
                    JSONObject x = element.getJSONObject(i);
                    String id = x.getString("id");
                    String nom =  x.getString("nom");
                    String appairage = x.getString("appairage");
                    if(appairage.equals("OK"))
                    {
                        appairage_count = appairage_count + 1;
                    }
                    Listview_games country = new Listview_games(id, nom, "image", "barcode", "statut", "emprunteur", appairage);
                    objet_list.add(country);
                }
            }

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

            return ("none"); // a voir
        }

        @Override
        protected void onPostExecute(String data)
        {
        }
    }

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

    class newHTTPDataHandler
    {
        String stream = null;

        public newHTTPDataHandler()
        {
        }

        public String GetHTTPData(String urlString)
        {
            try
            {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Check the connection status
                if(urlConnection.getResponseCode() == 200)
                {
                    // if response code = 200 ok
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                    // Read the BufferedInputStream
                    BufferedReader r = new BufferedReader(new InputStreamReader(in));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null)
                    {
                        sb.append(line);
                    }
                    stream = sb.toString();
                    // End reading...............

                    // Disconnect the HttpURLConnection
                    urlConnection.disconnect();
                }
                else
                {
                    // Do something
                }
            }

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

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

            finally
            {

            }

            // Return the data from specified url
            return stream;
        }
    }

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

    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 retour = input;

        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Intent intent=new Intent();
                intent.putExtra("TAG_NAME", retour );
                setResult(150,intent);
                finish();

            }
        });

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

        builder.show();

    }

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


}