package com.example.patrice.rerservation01;

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

import static com.example.patrice.rerservation01.JSONParser.json;
import static com.example.patrice.rerservation01.R.drawable.map;

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

    private static String url_requete_statistiques = "http://analog-design.net/WORKAREA/WEBSITE/reservation/statistiques.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>> statistique_liste;

    ListView liste_statistique;

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

    LayoutInflater inflater;

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

    HashMap<String, Integer> Hashmap_json = new HashMap<String, Integer>();
    HashMap<String, Integer> bis_Hashmap_json = new HashMap<String, Integer>();


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

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


        debug();


        try
        {
            tempo = new JSON_async().execute(url_requete_statistiques).get();

           // Collections.sort(tempo, new MapComparator("value"));

            /////// pour le tri en fonction du nombre d'emprunt (popularité du jeu)
            Set<Map.Entry<String, Integer>> set = Hashmap_json.entrySet();
            List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(set);
            Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
            {
                public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
                {
                    return (o2.getValue()).compareTo( o1.getValue() );
                }
            } );

        }

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

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

        statistiques_async aqw = new statistiques_async();

        aqw.execute();


    }

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

    public void debug()
    {

        try
        {
            tempo = new JSON_async().execute(url_requete_statistiques).get();

            /////// pour le tri en fonction du nombre d'emprunt (popularité du jeu)
            Set<Map.Entry<String, Integer>> set = Hashmap_json.entrySet();
            List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(set);
            Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
            {
                public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
                {
                    return (o2.getValue()).compareTo( o1.getValue() );
                }
            } );

        }

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

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


        int tmp = 123;

    }


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

    class xxxMapComparator implements Comparator<Map<String, String>>
    {
        private final String key;

        public xxxMapComparator(String key)
        {
            this.key = key;
        }

        public int compare(Map<String, String> first,
                           Map<String, String> second)
        {
            // TODO: Null checking, both for maps and values
            String firstValue = first.get(key);
            String secondValue = second.get(key);
            return firstValue.compareTo(secondValue);
        }
    }


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


            HashMap<String, Integer> xxmap = new HashMap<String, Integer>();

            // 361 jeu dans la database
            // indice 0 à 360

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

                        //HashMap<String, Integer> amap = new HashMap<String, Integer>();
                        //amap.put(TAG_JEU, 10);
                        //amap.put(TAG_TOTAL, 30);

                        //statistique_liste.add(amap);

                        xxmap.put( jeu, Integer.valueOf(total) );

                    }

                /////// pour le tri en fonction du nombre d'emprunt (popularité du jeu)
                Set<Map.Entry<String, Integer>> set = xxmap.entrySet();
                List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(set);
                Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
                {
                    public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
                    {
                        return (o2.getValue()).compareTo( o1.getValue() );
                    }
                } );

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

                for(Map.Entry<String, Integer> entry:list)
                {
                    System.out.println(entry.getKey()+" ==== "+entry.getValue());

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

                    amap.put(TAG_JEU, entry.getKey());
                    amap.put(TAG_TOTAL, String.valueOf(entry.getValue()));

                    alpha.put(TAG_JEU, entry.getKey());
                    alpha.put(TAG_TOTAL, String.valueOf(entry.getValue()));


                    statistique_liste.add(amap);


                }



              //  int count = Collections.frequency(new ArrayList<String>(map. .values()), "Red");
/*
                HashMap<String, Integer> party = new HashMap<String, Integer>();
                party.put("Jan",1);
                party.put("John",1);
                party.put("Brian",1);
                party.put("Dave",1);
                party.put("David",2);

                int count = Collections.frequency(party.values(), "1");
*/
                HashMap<String, String> xxx = new HashMap<String, String>();
                xxx.put("Jan","1");
                xxx.put("John","1");
                xxx.put("Brian","1");
                xxx.put("Dave","1");
                xxx.put("David","2");

                int count = Collections.frequency(xxx.values(), "1");

               count = Collections.frequency(xxmap.values(), "1");

                List<String> listing_keys = new ArrayList<String>();
                List<String> listing_values = new ArrayList<String>();

                for (int i = 0; i < list.size(); i++)
                {
                    listing_keys.add(list.get(i).getKey().toString());
                    listing_values.add(list.get(i).getValue().toString());
                }

                int ttt = Collections.frequency(listing_values, "1");

                String max = Collections.max(listing_values).toString();



                String[] namesArr = listing_keys.toArray(new String[listing_keys.size()]);


                List<Integer> keys_disponible  = new ArrayList<>();
                List<Integer> compte_repetition  = new ArrayList<>();

                List<String> head = listing_keys.subList(0, 4);

                int start = 0;
                int stop = 0;

                ArrayList<String> decoupage = new ArrayList<String>();

                for (int i = Integer.valueOf(max); i >= 0; i--)
                {
                    String element = String.valueOf(i);
                    int repetition = Collections.frequency(listing_values, element);
                    if(repetition != 0)
                    {
                        keys_disponible.add(i);
                        compte_repetition.add(repetition);

                        // creation dans range pour le découpage
                        start = 0;
                        stop =  start + repetition - 1;   // 6 2 - 1 1 1 1 - 1 1 1 1

                        if(start == stop)
                        {
                            List<String> provi = listing_keys.subList(start, stop);
                            decoupage.add(String.valueOf(provi));
                        }

                        if(start != stop )
                        {
                            List<Integer> temp  = new ArrayList<>();




                        }

                    }

                }

                String aaa= "7";


            }

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

            return("");

        }

        protected void onPostExecute(String s)
        {
/*
            list_statistique = (ListView) findViewById(R.id.list);

            ListAdapter adapter = new SimpleAdapter(   statistiques.this, statistique_liste,
                    R.layout.ddd, new String[] { TAG_JEU,  TAG_TOTAL},
                    new int[] { R.id.jeu, R.id.total });

            list_statistique.setAdapter(adapter);
*/

           // ((ListView) list_statistique).setAdapter(new List_Adapter(statistiques.this) ); // , statistique_liste));

          //  CustomAdapter adapter=new CustomAdapter(this, R.layout.statistique_layout, statistique_liste);
           //  list_statistique.setAdapter(adapter);

            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.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


        }
    }

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

    private class JSON_async 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;

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

            Map<String, String> retMap = new HashMap<String, String>();

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

            try
            {
                JSONObject jObj = null;
                jObj = new JSONObject(stream);

                //HashMap<String, String> pat_hashmap = new HashMap<String, String>();

                System.out.println(getMap(jObj));
               // pat_hashmap = (HashMap<String, String>) getMap(jObj);

                Map<String, Object> pat_hashmap = new HashMap<String, Object>();
                pat_hashmap =  getMap(jObj);

                element = jObj.getJSONArray(TAG_STATISTIQUES);


                HashMap<String, String> map;

                for (int i = 0; i < element.length(); i++)
                {
                    JSONObject x = element.getJSONObject(i);
                    pipo.add( x.getString(TAG_JEU) );
                }

                multiple( (ArrayList<String>) pipo );

                System.out.println("Number of duplicates elements = " + getDupCount((ArrayList<String>) pipo) );


                for (int i = 0; i < element.length(); i++)
                {
                    JSONObject x = element.getJSONObject(i);
                    map = new HashMap<String, String>();
                    map.put("jeu",  x.getString(TAG_JEU) );
                    map.put("total", x.getString(TAG_TOTAL) );

//                   Hashmap_json.put(  map.put("jeu", x.getString(TAG_JEU) ),  Integer.valueOf( map.put("total", x.getString(TAG_TOTAL)) ) );
//                    Hashmap_json.put(  map.put("jeu", String.valueOf(i) ),  Integer.valueOf( map.put("total", x.getString(TAG_TOTAL)) ) );

                    Hashmap_json.put(   String.valueOf(i)  , Integer.valueOf( x.getString(TAG_TOTAL))    );

                    bis_Hashmap_json.put( x.getString(TAG_JEU), Integer.valueOf( x.getString(TAG_TOTAL))  );

                    // Hashmap_json.put(  map.put("jeu", "toto" ),  Integer.valueOf( map.put("total", x.getString(TAG_TOTAL)) ) );


                    AppArrList.add(map);
                }

            }

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

            for (int i = 0; i < element.length(); i++)
            {
                String val = pipo.get(i);
                boolean b =  bis_Hashmap_json.containsKey(val);

                if(!b)
                {
                    Log.v("Missing : ",  pipo.get(i) );
                }
                else
                {
                    Log.v("OK : ", i + "  " + pipo.get(i) );
                }

            }



            return AppArrList;

        }

        @Override
        protected void onPostExecute(final ArrayList data)
        {

        }

    }



    public String getDupCount(ArrayList<String> l)
    {
        int cnt = 0;
        String val = "";
        HashSet<String> h = new HashSet<String>(l);

        List<String> tartuffe = new ArrayList<String>(l);
        Collections.sort(tartuffe);


        List<String> fruitList = new ArrayList<String>(h);
        Collections.sort(fruitList);


        String joined1 = TextUtils.join(" ", tartuffe );
        String joined2 = TextUtils.join(" ",fruitList);

        String d = diff(joined1, joined2);

        String doublon = "Discoveries : the Journals of Lewis & Clark VF";
        int detect = Collections.frequency(l, doublon);

        for (String token : h)
        {
            if (Collections.frequency(l, token) > 1)
                cnt++;


            val = token;
        }

        return (cnt + " " + val);
    }

    public static String diff(String str1, String str2) {
        int index = str1.lastIndexOf(str2);
        if (index > -1) {
            return str1.substring(str2.length());
        }
        return str1;
    }

    public void multiple(ArrayList<String> l)
    {
        String doublon = "Discoveries : the Journals of Lewis & Clark VF";
        int detect = Collections.frequency(l, doublon);

        for (int i = 0; i < l.size(); i++)
        {
                String val = l.get(i);
                detect = Collections.frequency(l, val);

            if(detect > 2)
            {
                Log.v("******* " , "Detection");
            }

        }

    }


    class MapComparator implements Comparator<Map<String, String>>{
        private final String key;

        public MapComparator(String key){
            this.key = key;
        }

        public int compare(Map<String, String> first,
                           Map<String, String> second){
            // TODO: Null checking, both for maps and values
            String firstValue = first.get(key);
            String secondValue = second.get(key);
            return firstValue.compareTo(secondValue);
        }
    }




    public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }

    private static Map getMap(JSONObject object) {
        Map<String, Object> map = new HashMap<String, Object>();

        Object jsonObject = null;
        String key = null;
        Object value = null;

        try {
            Iterator<String> keys = object.keys();
            while (keys.hasNext()) {

                key = null;
                value = null;

                key = keys.next();

                if (null != key && !object.isNull(key)) {
                    value = object.get(key);
                }

                if (value instanceof JSONObject) {
                    map.put(key, getMap((JSONObject) value));
                    continue;
                }

                if (value instanceof JSONArray) {
                    JSONArray array = ((JSONArray) value);
                    List list = new ArrayList();
                    for (int i = 0 ; i < array.length() ; i++) {
                        jsonObject = array.get(i);
                        if (jsonObject instanceof JSONObject) {
                            list.add(getMap((JSONObject) jsonObject));
                        } else {
                            list.add(jsonObject);
                        }
                    }
                    map.put(key, list);
                    continue;
                }

                map.put(key, value);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return map;
    }



    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 List_Adapter extends BaseAdapter
    {

        private LayoutInflater inflater;

        public List_Adapter(Context context) //, ArrayList<HashMap<String, String>> list)
        {
         //   statistique_liste = list;

        }

        @Override
        public int getCount()
        {
            return statistique_liste.size();
            //return IMAGE_URLS.length;
        }

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

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


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

            if(convertView == null)
            {
                view = inflater.inflate(R.layout.ddd, 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();
            }

            holder.jeu.setText(statistique_liste.get(position).get("jeu"));
            holder.total.setText(statistique_liste.get(position).get("total"));

            return view;
        }

        class ViewHolder
        {
            TextView jeu, total;
        }

    }
*/

/*
    private class CustomAdapter extends ArrayAdapter<HashMap<String, String>>
    {

        public CustomAdapter(statistiques_async context, int textViewResourceId, ArrayList<HashMap<String, String>> Strings)
        {


            super(context, textViewResourceId, Strings);
        }

        private class ViewHolder
        {
            TextView jeu, total;
        }

        ViewHolder viewHolder;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView==null)
            {
                //inflate the custom layout

                convertView = inflater.inflate(R.layout.ddd, null);
                viewHolder=new ViewHolder();


                viewHolder.jeu=(TextView) convertView.findViewById(R.id.jeu);
                viewHolder.total=(TextView) convertView.findViewById(R.id.total);

                convertView.setTag(viewHolder);

            }
            else
                viewHolder=(ViewHolder) convertView.getTag();

                viewHolder.jeu.setText(statistique_liste.get(position).get("jeu").toString());
                viewHolder.total.setText(statistique_liste.get(position).get("total").toString());

            return convertView;
        }

    }
*/
// http://android4beginners.com/2013/07/lesson-2-1-how-to-build-android-app-with-simple-but-powerful-linearlayout-plus-layout-orientation-as-well-as-size-and-weight-of-elements/
}
