package com.example.patrice.reservation02;


        import android.app.Activity;
        import android.content.Context;
        import android.content.DialogInterface;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.graphics.Bitmap;
        import android.graphics.Color;
        import android.os.AsyncTask;
        import android.support.v7.app.AlertDialog;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.text.Editable;
        import android.text.TextWatcher;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.AdapterView;
        import android.widget.BaseAdapter;
        import android.widget.EditText;
        import android.widget.Filterable;
        import android.widget.ImageView;
        import android.widget.ListView;
        import android.widget.SearchView;
        import android.widget.ShareActionProvider;
        import android.widget.TextView;
        import android.view.LayoutInflater;
        import android.widget.Toast;


        import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
        import com.nostra13.universalimageloader.core.DisplayImageOptions;
        import com.nostra13.universalimageloader.core.ImageLoader;
        import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
        import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
        import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
        import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
        import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
        import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
        import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

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

// http://tutorialsbuzz.com/2014/08/android-filter-custom-listview-baseadapter.html

public class retrait_02 extends AppCompatActivity implements  SearchView.OnQueryTextListener
{

    ListView listView;

    CustomAdapter adapter;
    SearchView search_view;

    JSONArray element = null;
    JSONParser jParser = new JSONParser();

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

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

    int nb_retraits = 0;

    private Activity activity;
    private String[] data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader;

    ArrayList<Listview_games> countrylist;
    String listview_selection;

    Menu mMenu;

    Menu menu;

    MenuItem toti;

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

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

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

        String urlString = "http://analog-design.net/WORKAREA/WEBSITE/reservation/query05.php";

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

        int nb_jeu = countrylist.size();

        getSupportActionBar().setTitle("   Jeux CE " + nb_jeu + " (" + nb_retraits +")" );
        getSupportActionBar().setLogo(R.drawable.books);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(true);


        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(retrait_02.this);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        ImageLoader.getInstance().init(config.build());

        adapter = new CustomAdapter(getApplicationContext(), countrylist);
        listView.setAdapter(adapter);

        search_view.setOnQueryTextListener(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {

                // ArrayList<Listview_games> countrylist = null;

                TextView val = (TextView) view.findViewById(R.id.nom);
                listview_selection = val.getText().toString();

                String concate = null;

                try {
                    concate = new requete_infos_jeu().execute(listview_selection).get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

                String[] parts = concate.split("&");

                //concate = id + "&" + nom + "&" + statut;

                String position_mysql = parts[0];

                if(parts[2].equals("retrait"))
                {
                    dialog_indisponible_retrait();
                }
                else
                {
                    Intent i = new Intent(getApplicationContext(), emprunter_by_listview.class);
                    i.putExtra("jeu", parts[1] ); // listview_selection
                    startActivity(i);
                }
            }
        });

    }

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

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



// http://tutorialsbuzz.com/2014/08/android-filter-custom-listview-baseadapter.html

    // https://gist.github.com/DeepakRattan/26521c404ffd7071d0a4

    // http://camposha.info/source/android-custom-filtersearch-listview-listview-images-text-baseadapter-source

    // http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/

    // http://theopentutorials.com/tutorials/android/listview/android-custom-listview-with-image-and-text-using-baseadapter/  ?????


    private class ProcessJSON extends AsyncTask<String, Void, ArrayList>
    {

        @Override
        protected void onPreExecute()
        {
        }

        @Override
        protected ArrayList doInBackground(String... strings)
        {
            String stream = null;
            String urlString = strings[0];

            newHTTPDataHandler hh = new newHTTPDataHandler();
            stream = hh.GetHTTPData(urlString);

            nb_retraits = 0;

            try
            {
                JSONObject jObj = null;
                jObj = new JSONObject(stream);
                element = jObj.getJSONArray("result");

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

                    int indice = i + 1;

                    String path = String.valueOf(indice);

                    String image = "http://analog-design.net/WORKAREA/WEBSITE/reservation/IMG/" + path + ".jpg";

                    //String image =  x.getString("image");
                    String  barcode = x.getString("barcode");
                    String  statut = x.getString("statut");
                    String  emprunteur = x.getString("emprunteur");

                    if( x.getString("statut").equals("retrait") )
                    {
                        nb_retraits = nb_retraits + 1;
                    }

                    if(barcode.equals("null"))
                    {
                        barcode  = "Barcode : ???";
                    }

                    // statut = "Statut :" + statut;

                    Listview_games country = new Listview_games(id, nom, image, barcode, statut, emprunteur, "");
                    countrylist.add(country);
                }

            }

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


            return AppArrList; // a voir

        }

        @Override
        protected void onPostExecute(final ArrayList 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;
        }
    }


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

    //onPrepareOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        this.menu = menu;

        getMenuInflater().inflate(R.menu.test_menu, menu);

        mMenu = menu;
        mMenu.findItem(R.id.action_panier).setVisible(false);

        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        boolean key_existe = sp.contains("size");
        if(key_existe)
        {
            mMenu.findItem(R.id.action_panier).setVisible(true);
            mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
        }


        // Get the ActionProvider for later usage
        //provider = (ShareActionProvider) menu.findItem(R.id.action_panier)       .getActionProvider();

        //   toti = menu.findItem(R.id.action_panier);

        return true;
    }


    //gère le click sur une action de l'ActionBar
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()){
            case R.id.action_panier:
                f1();
                return true;
            //case R.id.action_aide:
            //    f2();
            //    return true;
            case R.id.action_a_propos:
                return true;
            case android.R.id.home:
                this.finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /*
        public boolean onPrepareOptionsMenu(Menu menu){
    //code here

            this.menu = menu;

            getMenuInflater().inflate(R.menu.test_menu, menu);

            mMenu = menu;
            mMenu.findItem(R.id.action_panier).setVisible(false);

            SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            boolean key_existe = sp.contains("size");
            if(key_existe)
            {
                mMenu.findItem(R.id.action_panier).setVisible(true);
                mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
            }
            else {
                mMenu.findItem(R.id.action_panier).setVisible(false);
            }

            return super.onPrepareOptionsMenu(menu);
        }
    */
    public void f1()
    {
        Intent i = new Intent(getApplicationContext(), emprunter_by_listview.class);
        startActivity(i);

        Toast.makeText(getApplicationContext(), " F1 ", Toast.LENGTH_SHORT).show();

    }

    public void f2()
    {
        Toast.makeText(getApplicationContext(), " F2 ", Toast.LENGTH_SHORT).show();

    }




    @Override
    public void onRestart()
    {
        super.onRestart();

        //   Toast.makeText(getApplicationContext(), " RESTART ", Toast.LENGTH_LONG).show();

        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        boolean key_existe = sp.contains("size");
        if(key_existe)
        {
            mMenu.findItem(R.id.action_panier).setVisible(true);
            mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
        }
        else {
            mMenu.findItem(R.id.action_panier).setVisible(false);
        }

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

        String urlString = "http://analog-design.net/WORKAREA/WEBSITE/reservation/query05.php";

        tempo.clear();

        countrylist.clear();

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

        int nb_jeu = countrylist.size();

        getSupportActionBar().setTitle("   Jeux CE " + nb_jeu + " (" + nb_retraits +")" );

        adapter = new CustomAdapter(getApplicationContext(), countrylist);
        listView.setAdapter(adapter);

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

    }

    private void dialog_indisponible_retrait()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Attention !");
        builder.setMessage("Ce jeu est indisponible, s'adresser à l'emprunteur indiquer ci-dessous");

        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 requete_infos_jeu extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        protected String doInBackground(String... args)
        {
            String jeu_nom = args[0];

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("nom", jeu_nom));

            JSONObject json = jParser.makeHttpRequest(url_requete_infos_jeu, "GET", params);
            Log.d("Affiche format JSON: ", json.toString());

            String concate = null;

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1)
                {
                    JSONArray productObj = json.getJSONArray("jeu");
                    JSONObject product = productObj.getJSONObject(0);
                    String id = product.getString("id");
                    String nom = product.getString("nom");
                    String statut = product.getString("statut");
                    concate = id + "&" + nom + "&" + statut;

                } else {
                    // erreur non prévu
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return (concate);
        }

        protected void onPostExecute(final ArrayList s)
        {

        }
    }

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



}

