package org.keyscience;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class JSONRanks {
    public static String ranksJsonDir = "http://keyscience.org/wp-content/app/userprofile/userRanks.json";
    public static HashMap<String, String> hm = new HashMap<>();
    @Test
    public void testRanks() throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(ranksJsonDir);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            String jsonInput = buffer.toString();

            readRankJSON(jsonInput);

        } catch (Exception e) {

        }
    }

    private static void readRankJSON(String inputLine) {
    // Read out user attributes for displaying in TextView, ImageView

        List<HashMap<String, String>> results = new ArrayList<>();
        JSONArray jArray;
        try {
            jArray = new JSONArray(inputLine);

            for (int i = 0; i < jArray.length(); i++) {
                hm = new HashMap<>();

                JSONObject json_data = jArray.getJSONObject(i);

                hm.put("Rank", json_data.getString("Rank"));
                hm.put("Points", json_data.getString("Points"));

                results.add(hm);
            }

            int userPoints = 800;

            HashMap.Entry<String, String> maxEntry = null;

            for (HashMap.Entry<String, String> entry : hm.entrySet())
                if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
                    if ( userPoints > Integer.valueOf(entry.getValue()) )
                        System.out.printf("User is %s Rank \n\n", hm.get("Rank"));
                    else
                        for (HashMap<String, String> model : results)
                            if ( userPoints <= Integer.valueOf(model.get("Points")) ) {
                                System.out.printf("User is %s Rank \n\n", model.get("Rank"));
                                break;
                            }

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