package com.droideve.apps.dealify.activities;

import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.network.VolleySingleton;
import com.droideve.apps.dealify.network.api_request.SimpleRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.droideve.apps.dealify.appconfig.AppConfig.APP_DEBUG;

public class DeliveryAnalytics extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    //GET CATEGORIES FROM  DATABASE
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_description)
    TextView toolbarDescription;

    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;

    @BindView(R.id.item_wrapper)
    LinearLayout item_wrapper;

    private HashMap<String, String> listAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_analytics);

        ButterKnife.bind(this);

        initToolbar();

        setupRefresh();

        listAnalytics = new HashMap<>();

        getMyAnalyticsFromAPI();


    }

    private void setupRefresh() {
        refresh.setOnRefreshListener(this);


        refresh.setColorSchemeResources(
                R.color.colorAccent,
                R.color.colorAccent,
                R.color.colorAccent,
                R.color.colorAccent
        );
    }


    public void initToolbar() {

        toolbar = findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbarDescription.setVisibility(View.GONE);

        toolbarTitle.setText(R.string.revenue_analytics);


    }


    private void getMyAnalyticsFromAPI() {

        refresh.setRefreshing(true);
        RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();

        int user_id = SessionsController.getSession().getUser().getId();
        String user_token = SessionsController.getSession().getUser().getToken();

        SimpleRequest request = new SimpleRequest(Request.Method.POST,
                Constances.API.API_ANALYTICS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                refresh.setRefreshing(false);

                try {

                    if (APP_DEBUG) {
                        Log.e("analytics", response);
                    }

                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("success") == 1) {
                        JSONObject analyticsjsonObject = jsonObject.getJSONObject("result");
                        Iterator<String> keys = analyticsjsonObject.keys();

                        while (keys.hasNext()) {
                            String key = keys.next();
                            listAnalytics.put(key, analyticsjsonObject.get(key).toString());
                        }

                        populateDataOnList(item_wrapper, listAnalytics);

                    }


                } catch (JSONException e) {
                    //send a rapport to support
                    e.printStackTrace();


                } finally {
                    refresh.setRefreshing(false);

                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (APP_DEBUG) {
                    Log.e("ERROR", error.toString());
                }

                refresh.setRefreshing(false);

            }


        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("user_id", String.valueOf(user_id));
                params.put("user_token", user_token);

                if (APP_DEBUG) {
                    Log.e("revenue_analytics", "  params  :" + params.toString());
                }


                return params;
            }

        };

        request.setRetryPolicy(new DefaultRetryPolicy(SimpleRequest.TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        queue.add(request);


    }


    private void populateDataOnList(LinearLayout listItems, HashMap<String, String> listAnalytics) {

        listItems.removeAllViews();

        for (Map.Entry<String, String> entry : listAnalytics.entrySet()) {


            LinearLayout total_price_layout = new LinearLayout(this);
            total_price_layout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams layout_379 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layout_379.gravity = ConstraintLayout.LayoutParams.END;
            layout_379.leftMargin = (int) this.getResources().getDimension(R.dimen.spacing_large);
            layout_379.rightMargin = (int) this.getResources().getDimension(R.dimen.spacing_large);
            layout_379.topMargin = (int) this.getResources().getDimension(R.dimen.spacing_medium);
            layout_379.bottomMargin = (int) this.getResources().getDimension(R.dimen.spacing_medium);

            total_price_layout.setLayoutParams(layout_379);

            TextView titleTxt = new TextView(this);
            titleTxt.setTypeface(titleTxt.getTypeface(), Typeface.BOLD);
            titleTxt.setTextSize(18);
            titleTxt.setTextColor(this.getResources().getColor(R.color.black));
            LinearLayout.LayoutParams layout_335 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            titleTxt.setLayoutParams(layout_335);
            total_price_layout.addView(titleTxt);

            TextView valueTxt = new TextView(this);
            valueTxt.setTypeface(valueTxt.getTypeface(), Typeface.BOLD);
            valueTxt.setTextColor(this.getResources().getColor(R.color.grey_60));
            valueTxt.setTextSize(16);
            LinearLayout.LayoutParams layout_991 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            //layout_991.leftMargin = (int) this.getResources().getDimension(R.dimen.spacing_middle);
            layout_991.topMargin = (int) this.getResources().getDimension(R.dimen.spacing_middle);
            valueTxt.setLayoutParams(layout_991);
            //valueTxt.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);

            total_price_layout.addView(valueTxt);

            //dynamic content
            titleTxt.setText(entry.getKey().replace("_", " ").toUpperCase());
            valueTxt.setText(entry.getValue());

            listItems.addView(total_price_layout);

        }


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (android.R.id.home == item.getItemId()) {
            finish();
            overridePendingTransition(R.anim.righttoleft_enter, R.anim.righttoleft_exit);
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        overridePendingTransition(R.anim.righttoleft_enter, R.anim.righttoleft_exit);

    }

    @Override
    public void onRefresh() {

        getMyAnalyticsFromAPI();
    }
}