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.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(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_reportlist, container, false);
        parent = (ProfileActivity)getActivity();

        uid = getArguments().getString("uid",parent.user.get(SessionManager.KEY_UID));

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

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

        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parentview, View view, int position, long id) {
                try {
                    if(resultList.get(position).getInt("status") == 1){
                        parent.gotoViewReportActivity(resultList.get(position).getInt("id"));
                    }

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

        return view;
    }

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

        String tag_string_req = "getincidentswithpositionfromid";
        StringRequest strReq = getStringRequestGetIncidentsWithPositionFromUserID();
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

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

            @Override
            public void onResponse(String 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");
                        Log.e(TAG, "Error getting incident list (Server returned error): " + errorMsg);
                    }

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

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "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;
            }
        };
    }

}
