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.content.ContextCompat;
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 TAG = MainActivity.class.getSimpleName();

    private Handler mHandler  = new Handler();
    private TextView notificationStatus;



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

        userHasToBeLoggedIn();
        showDialog();

        initButtons();
    }

    private void initButtons() {
        Button 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(ContextCompat.getColor(getApplicationContext(),R.color.white))
                .sizeDp(24);

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

        Button 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(ContextCompat.getColor(getApplicationContext(), R.color.white))
                .sizeDp(24);

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

    Runnable mHandlerTask = new Runnable()
    {
        @Override
        public void run() {
            requestNumberOfIncidents();

            notificationStatus = (TextView) findViewById(R.id.lbl_main_notifystatus_status);
            if(session.getNotificationEnabled()){
                if(session.getNotificationServiceReady()){
                    notificationStatus.setText(getString(R.string.txt_notifystatus_activated));
                    notificationStatus.setTextColor(getResources().getColor(R.color.md_green_400));
                }else{
                    notificationStatus.setText(getString(R.string.txt_notifystatus_activatedbutnotready));
                    notificationStatus.setTextColor(getResources().getColor(R.color.md_yellow_400));
                }
            }else{
                notificationStatus.setText(getString(R.string.txt_notifystatus_deactivated));
                notificationStatus.setTextColor(getResources().getColor(R.color.md_red_400));
            }

            mHandler.postDelayed(mHandlerTask, AppConfig.UPDATE_COUNT_INTERVAL);
        }
    };

    private void requestNumberOfIncidents() {
        StringRequest strReq = getStringRequestIncidentCount();
        String tag_string_req = "req_incidents";
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

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

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

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

                    if (!error) {
                        JSONObject jCount = jObj.getJSONObject("msg");

                        displayNumberOfIncidents(jCount);
                    } 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", AppConfig.REST_GET_NUMOFINCIDENTS);
                params.put("uid", user.get(SessionManager.KEY_UID));
                params.put("token", user.get(SessionManager.TOKEN));
                return params;
            }
        };
    }

    private void displayNumberOfIncidents(JSONObject jCount) throws JSONException {
        TextView count =  (TextView) findViewById(R.id.txt_main_incidents);
        DecimalFormat nf = new DecimalFormat();
        String decimalNumber = nf.format(jCount.getInt("total"));
        count.setText(decimalNumber);
    }

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

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

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

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

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

    @Override
    protected String getActivityName() {
        return getResources().getString(R.string.title_activity_start);
    }



}
