package com.droideve.apps.dealify.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
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.adapter.lists.CategoriesListAdapter;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Category;
import com.droideve.apps.dealify.controllers.categories.CategoryController;
import com.droideve.apps.dealify.network.VolleySingleton;
import com.droideve.apps.dealify.network.api_request.ApiRequest;
import com.droideve.apps.dealify.network.api_request.ApiRequestListeners;
import com.droideve.apps.dealify.network.api_request.SimpleRequest;
import com.droideve.apps.dealify.parser.Parser;
import com.droideve.apps.dealify.parser.api_parser.CategoryParser;
import com.droideve.apps.dealify.parser.tags.Tags;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.RealmList;

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


public class CategoriesActivity extends GlobalActivity implements CategoriesListAdapter.ClickListener, SwipeRefreshLayout.OnRefreshListener {

    //GET CATEGORIES FROM  DATABASE
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarDescription;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;

    private CategoriesListAdapter adapter;
    private RequestQueue queue;

    private int parent_id;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_categories);
        ButterKnife.bind(this);

        initToolbar();

        toolbarTitle.setText(R.string.categories);

        list = findViewById(R.id.list);
        list.setVisibility(View.VISIBLE);

        adapter = new CategoriesListAdapter(this, getData(), false, null, 0, 0, false);


        list.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        list.setLayoutManager(mLayoutManager);
        list.setAdapter(adapter);

        adapter.setClickListener(this);

        refresh.setOnRefreshListener(this);


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


        getCatsFromAPIs();


        ((SimpleItemAnimator) list.getItemAnimator()).setSupportsChangeAnimations(false);

    }

    public List<Category> getData() {

        List<Category> results = new ArrayList<>();

        return results;
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public void itemClicked(View view, final int position) {

        HashMap<String, Object> searchParams = new HashMap<>();
        searchParams.put("module", Constances.ModulesConfig.PRODUCT_MODULE);
        searchParams.put("category_id", adapter.getItem(position).getNumCat());
        searchParams.put("category_selected_index", position);

        Intent intent = new Intent(this, ResultFilterActivity.class);
        intent.putExtra("searchParams", searchParams);
        startActivity(intent);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (android.R.id.home == item.getItemId()) {
            finish();
            
        }

        return super.onOptionsItemSelected(item);
    }

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

        

    }


    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);

    }


    @Override
    public void onRefresh() {
        getCatsFromAPIs();
    }


    private void getCatsFromAPIs() {

        refresh.setRefreshing(true);

        try {
            parent_id = getIntent().getExtras().getInt("parent_id",-1);
        }catch (Exception e){
            parent_id = -1;
        }

        ApiRequest.newPostInstance(Constances.API.API_USER_GET_CATEGORY, new ApiRequestListeners() {
            @Override
            public void onSuccess(Parser parser) {
                final CategoryParser mCategoryParser = new CategoryParser(parser);

                if (mCategoryParser.getSuccess() == 1
                        && mCategoryParser.getCategories().size() > 0) {

                    RealmList<Category> list = mCategoryParser.getCategories();
                    adapter.clear();
                    for (int i = 0; i < list.size(); i++) {
                        adapter.addItem(list.get(i));
                    }
                    CategoryController.insertCategories(list);

                }

                refresh.setRefreshing(false);

            }

            @Override
            public void onFail(Map<String, String> errors) {

            }
        }, Map.of(
                "parent", String.valueOf(parent_id)
        ));


    }


}
