package org.deke.risk.riskahead.fragment;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.deke.risk.riskahead.ProfileActivity;
import org.deke.risk.riskahead.R;
import org.deke.risk.riskahead.helper.AppConfig;
import org.deke.risk.riskahead.helper.AppController;
import org.deke.risk.riskahead.adapter.Top10ListAdapter;
import org.deke.risk.riskahead.helper.SessionManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Top10Fragment extends Fragment {

    private final static String TAG = ProfileStatisticsFragment.class.getSimpleName();
    private ProfileActivity parent;

    ListView myListView;
    ListAdapter myListAdapter;
    List<JSONObject> resultList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top10list, container, false);
        parent = (ProfileActivity)getActivity();

        myListView = (ListView) view.findViewById(R.id.lv_top10list);

        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parentview, View view, int position, long id) {
                try {
                    parent.gotoProfileActivity(resultList.get(position).getString("id"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        if(resultList == null || resultList.size() == 0) getTop10ForList();

        return view;
    }

    private void getTop10ForList() {
        ((ProfileActivity)getActivity()).showDialog();

        StringRequest strReq2 = getStringRequestTop10();
        String tag_string_req2 = "req_top10";
        AppController.getInstance().addToRequestQueue(strReq2, tag_string_req2);
    }


    private StringRequest getStringRequestTop10() {
        return new StringRequest(Request.Method.POST, AppConfig.URL_DEFAULT, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Top 10 stats: " + response);

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        JSONArray users = jObj.getJSONArray("msg");
                        resultList = new ArrayList<>();

                        for(int i=0;i<users.length();i++){
                            JSONObject user = users.getJSONObject(i);
                            resultList.add(user);
                        }

                        myListAdapter = new Top10ListAdapter(
                                parent.getApplicationContext(),
                                resultList);

                        myListView.setAdapter(myListAdapter);

                    } else {
                        String errorMsg = jObj.getString("error_msg");
                        Log.e(TAG, "Error getting top 10 stats (Server returned error): " + errorMsg);
                        parent.showMessage(getResources().getString(R.string.txt_errormsg_gettop10));
                    }

                    ((ProfileActivity)getActivity()).hideDialog();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error getting top 10 stats: " + error.getMessage());
                ((ProfileActivity)getActivity()).hideDialog();
                parent.showMessage(getString(R.string.errormsg_couldnotretrieve));

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("tag", AppConfig.REST_GET_TOP10);
                params.put("uid", parent.user.get(SessionManager.KEY_UID));
                params.put("token", parent.user.get(SessionManager.TOKEN));

                return params;
            }
        };
    }

}
