package com.example.patrice.reservation02;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


import org.apache.http.NameValuePair;
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.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;


public class statistiques_02 extends AppCompatActivity
{
    JSONParser jParser = new JSONParser();

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

    private static final String TAG_STATISTIQUES = "statistiques";
    private static final String TAG_JEU = "jeu";
    private static final String TAG_TOTAL = "total";

    JSONArray datas = null;

    ArrayList<HashMap<String, String>> tempo = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String, String>> statistique_liste = new ArrayList<HashMap<String, String>>();

    ListView liste_statistique;

    private static LayoutInflater inflater=null;

    private Activity activity;

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

        liste_statistique = (ListView) findViewById(R.id.liste_statistique);

        //get the LayoutInflater for inflating the customomView
        //inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        getSupportActionBar().setTitle(" Popularité des jeux"); //
        getSupportActionBar().setLogo(R.drawable.podium);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

       // statistiques_async aqw = new statistiques_async();
       // aqw.execute();

        // tâche de fond
        try
        {
            tempo = new ProcessJSON().execute(url_requete_statistiques).get();
        }

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

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

        liste_statistique = (ListView) findViewById(R.id.liste_statistique);

        ((ListView) liste_statistique).setAdapter(new TestAdapter(statistiques_02.this, tempo ));

    }

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

    // pour le retour - inclus dans l'action bar ( < )
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

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

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

            JSONArray element = null;

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

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

                for (int i = 0; i < element.length(); i++)
                {
                        JSONObject c = element.getJSONObject(i);
                        String jeu = c.getString(TAG_JEU);
                        String total = c.getString(TAG_TOTAL);

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_JEU, jeu);
                        map.put(TAG_TOTAL, total );
                        statistique_liste.add(map);
                }

            }

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


            return statistique_liste;

        }

        @Override
        protected void onPostExecute(final ArrayList data)
        {

        }

    }

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


    class statistiques_async 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_requete_statistiques, "GET", params);
            Log.v("JSON: ", json.toString());

            try
            {
                datas = json.getJSONArray(TAG_STATISTIQUES);

                for (int i = 0; i < datas.length(); i++)
                {
                    JSONObject c = datas.getJSONObject(i);
                    String jeu = c.getString(TAG_JEU);
                    String total = c.getString(TAG_TOTAL);

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_JEU, jeu);
                    map.put(TAG_TOTAL, total ); // Integer.valueOf(total)
                    statistique_liste.add(map);
                }
            }

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

            return("");

        }

        protected void onPostExecute(String s)
        {
            //String[] from={"jeu","total"};//string array
            //int[] to={R.id.jeu,R.id.total};//int array of views id's
            //SimpleAdapter simpleAdapter=new SimpleAdapter(statistiques_02.this, statistique_liste , R.layout.ddd, from, to);//Create object and set the parameters for simpleAdapter
            //liste_statistique.setAdapter(simpleAdapter);//sets the adapter for listView

            //liste_statistique = (ListView) findViewById(R.id.liste_statistique);

            //((ListView) liste_statistique).setAdapter(new TestAdapter(statistiques_02.this.toString(), statistique_liste ));

        }
    }

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

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

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

    public class TestAdapter extends BaseAdapter {


        private LayoutInflater inflater;
        ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public TestAdapter(Activity a, ArrayList<HashMap<String, String>> list_affichage)
        {
            activity = a;
            MyArr = list_affichage;

            inflater = LayoutInflater.from(activity);

        }

        @Override
        public int getCount()
        {
            return MyArr.size();

        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View view = convertView;
            final ViewHolder holder;

            if (convertView == null)
            {

                view = inflater.inflate(R.layout.statistiques_row_layout, parent, false);
                holder = new ViewHolder();

                holder.jeu = (TextView) view.findViewById(R.id.jeu);
                holder.total = (TextView) view.findViewById(R.id.total);

                view.setTag(holder);
            }

            else
            {
                holder = (ViewHolder) view.getTag();
            }

            int indice = position + 1;
            holder.jeu.setText(indice + "  " + MyArr.get(position).get("jeu"));
            holder.total.setText(MyArr.get(position).get("total"));

            return view;
        }
    }

    static class ViewHolder
    {
        TextView jeu, total;
    }
}
