package org.deke.risk.riskahead;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;

import org.deke.risk.riskahead.helper.AppConfig;
import org.deke.risk.riskahead.helper.AppController;
import org.deke.risk.riskahead.helper.BaseActivity;
import org.deke.risk.riskahead.helper.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends BaseActivity{

    private final static String mActivityTitle = "RiskAhead";
    private final static String TAG = MainActivity.class.getSimpleName();
    public String msg_input;

    public static FragmentManager fragmentManager;

    Handler mHandler  = new Handler();

    private final static int INTERVAL = 1000 * 20; //20 seconds
    private TextView count;

    private Button report;
    private Button map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userHasToBeLoggedIn();

        count =  (TextView) findViewById(R.id.txt_main_incidents);

        Intent intent = getIntent();
        msg_input = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        fragmentManager = getSupportFragmentManager();

        report = (Button) findViewById(R.id.btn_main_report);
        report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoReportActivity();
            }
        });

        Drawable reportIcon = new IconicsDrawable(this)
                .icon(GoogleMaterial.Icon.gmd_room)
                .color(getResources().getColor(R.color.white))
                .sizeDp(24);

        report.setCompoundDrawables(reportIcon, null, null, null);

        map = (Button) findViewById(R.id.btn_main_viewmap);

        map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoMapActivity();
            }
        });

        Drawable mapIcon = new IconicsDrawable(this)
                .icon(GoogleMaterial.Icon.gmd_map)
                .color(getResources().getColor(R.color.white))
                .sizeDp(24);

        map.setCompoundDrawables(null, null, mapIcon, null);

    }




    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected String getActivityName() {
        return mActivityTitle;
    }

    @Override
    protected void onPause(){
        super.onPause();
        stopRepeatingTask();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
    }

    @Override
    protected void onResume(){
        super.onResume();
        navDrawer.setSelection(mainAvtivityID,false);
        startRepeatingTask();
    }

    Runnable mHandlerTask = new Runnable()
    {
        @Override
        public void run() {
            StringRequest strReq = getStringRequestIncidentCount();
            String tag_string_req = "req_incidents";
            AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
            mHandler.postDelayed(mHandlerTask, INTERVAL);
        }
    };

    void startRepeatingTask()
    {
        mHandlerTask.run();
    }

    void stopRepeatingTask()
    {
        mHandler.removeCallbacks(mHandlerTask);
    }

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

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Incident count: " + response);

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

                    if (!error) {
                        JSONObject jCount = jObj.getJSONObject("msg");
                        DecimalFormat nf = new DecimalFormat();
                        String decimalNumber = nf.format(jCount.getInt("total"));
                        count.setText(decimalNumber);
                    } else {
                        String errorMsg = jObj.getString("error_msg");
                        Log.e(TAG, "Error getting incident count (server returned error): " + errorMsg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error getting incident count: " + error.getMessage());
                showMessage(getString(R.string.errormsg_couldnotretrieve));
                stopRepeatingTask();
            }
        }) {

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