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.ReportListAdapter;
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 ReportListFragment extends Fragment{
    private final static String TAG = ReportListFragment.class.getSimpleName();

    private ProfileActivity parent;

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

    private String uid;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_reportlist, container, false);

        parent = (ProfileActivity)getActivity();
        Bundle arguments = getArguments();
        if(arguments != null && parent != null){
            uid = getArguments().getString("uid",parent.user.get(SessionManager.KEY_UID));
        }else{
            FirebaseCrashlytics.getInstance().log("Could either not get arguments or parent activity");
        }

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

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

        myListView.setOnItemClickListener((parentview, view1, position, id) -> {
            try {
                if(resultList.get(position).getInt("status") == 1){
                    parent.gotoViewReportActivity(resultList.get(position).getInt("id"));
                }
            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("Catched JSONException");
                FirebaseCrashlytics.getInstance().recordException(e);
            }
        });

        return view;
    }

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

            String tag_string_req = "getincidentswithpositionfromid";
            StringRequest strReq = getStringRequestGetIncidentsWithPositionFromUserID();
            AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
        }else{
            FirebaseCrashlytics.getInstance().log("Could not get parent activity");
        }
    }

    private StringRequest getStringRequestGetIncidentsWithPositionFromUserID() {
        return new StringRequest(Request.Method.POST, AppConfig.REST_GET_INCIDENTS_FROMUSERID, response -> {
            Log.d(TAG, "Map positions response with ID: " + response);

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) {
                    JSONArray incidents = jObj.getJSONArray("msg");
                    resultList = new ArrayList<>();

                    for(int i=0;i<incidents.length();i++){

                        JSONObject incident = incidents.getJSONObject(i);
                        resultList.add(incident);
                    }

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

                    myListView.setAdapter(myListAdapter);

                } else {
                    String errorMsg = jObj.getString("error_msg");
                    FirebaseCrashlytics.getInstance().log("Error getting incident list (Server returned error): " + errorMsg);
                }

                ProfileActivity activity = (ProfileActivity) getActivity();
                if(activity != null){
                    activity.hideDialog();
                }else{
                    FirebaseCrashlytics.getInstance().log("Could not get parent activity");
                }
            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("Catched JSONException");
                FirebaseCrashlytics.getInstance().recordException(e);
            }
        }, error -> {
            FirebaseCrashlytics.getInstance().log("Error getting incident list: " + error.getMessage());
            parent.handleVolleyErrorResponse();
            parent.hideDialog();
        }) {

            @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));
                params.put("userincidentid", uid);

                return params;
            }
        };
    }
}
