package org.deke.risk.riskahead.fragment;

import androidx.annotation.NonNull;
import androidx.fragment.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.ListAdapter;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.google.firebase.crashlytics.FirebaseCrashlytics;

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;

/**
 *
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 *
 */
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(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top10list, container, false);
        parent = (ProfileActivity)getActivity();

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

        myListView.setOnItemClickListener((parentview, view1, position, id) -> {
            try {
                parent.gotoProfileActivity(resultList.get(position).getString("id"));
            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("JSONException caught");
                FirebaseCrashlytics.getInstance().recordException(e);
            }
        });

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

        return view;
    }

    private void getTop10ForList() {
        ProfileActivity activity = (ProfileActivity) getActivity();
        if(activity != null){
            activity.showDialog();

            StringRequest strReq2 = getStringRequestTop10();
            String tag_string_req2 = "req_top10";
            AppController.getInstance().addToRequestQueue(strReq2, tag_string_req2);
        }else{
            FirebaseCrashlytics.getInstance().log("Could not get parent Activity");
        }
    }

    private StringRequest getStringRequestTop10() {
        return new StringRequest(Request.Method.POST, AppConfig.REST_GET_TOP10, 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");
                    FirebaseCrashlytics.getInstance().log("Error getting top 10 stats (Server returned error): " + errorMsg);
                    parent.showMessage(getResources().getString(R.string.txt_errormsg_gettop10));
                }

                ProfileActivity activity = (ProfileActivity) getActivity();
                if(activity != null){
                    activity.hideDialog();
                }else{
                    FirebaseCrashlytics.getInstance().log("Could not get parent Activity");
                }

            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("JSONException caught");
                FirebaseCrashlytics.getInstance().recordException(e);
            }

        }, error -> {
            FirebaseCrashlytics.getInstance().log("Error getting top 10 stats: " + error.getMessage());

            ProfileActivity activity = (ProfileActivity) getActivity();
            if(activity != null){
                activity.hideDialog();
                activity.handleVolleyErrorResponse();
            }else{
                FirebaseCrashlytics.getInstance().log("Could not get parent Activity");
            }
        }) {

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

                return params;
            }
        };
    }

}
