package ch.pizzalemon.android.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import butterknife.BindView;
import butterknife.ButterKnife;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.adapter.recycler.MenuProductRecyclerAdapter;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseArray;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.CampaignModel;
import ch.pizzalemon.android.model.menu.MenuProductModel;
import ch.pizzalemon.android.view.AppToolbar;
import ch.pizzalemon.android.view.GridSpacesItemDecoration;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CampaignProductListActivity extends BaseActivity {

    @BindView(R.id.campaignProductsAppToolbar) AppToolbar campaignProductsAppToolbar;
    @BindView(R.id.campaignProductRecyclerView) RecyclerView campaignProductRecyclerView;

    private ArrayList<MenuProductModel> menuProductList = new ArrayList<>();
    private MenuProductRecyclerAdapter menuProductRecyclerAdapter;
    private CampaignModel campaignModel;

    private int REQUEST_CODE_CAMPAIGN_PRODUCT_PROPERTIES = 4756;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_campaign_product_list);
        ButterKnife.bind(this);
        getDataFromIntent();
        initViews();
        getCampaignProducts();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_CAMPAIGN_PRODUCT_PROPERTIES && resultCode == RESULT_OK){
            setResult(RESULT_OK);
            finish();
        }
    }

    private void getDataFromIntent(){
        campaignModel = (CampaignModel) getIntent().getSerializableExtra("campaignModel");
    }

    private void initViews(){
        campaignProductsAppToolbar.setTitle(campaignModel.getName());
        initRecyclerView();
    }

    private void initRecyclerView(){
        GridLayoutManager layoutManager = new GridLayoutManager(BaseActivity.currentActivity, 2);
        campaignProductRecyclerView.setLayoutManager(layoutManager);
        menuProductRecyclerAdapter = new MenuProductRecyclerAdapter(
                menuProductList,
                true,
                new RecyclerItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent productPropertiesIntent = new Intent(BaseActivity.currentActivity, CampaignProductDetailsActivity.class);
                        productPropertiesIntent.putExtra("menuProductModel", menuProductList.get(position));
                        productPropertiesIntent.putExtra("campaignModel", campaignModel);
                        //productPropertiesIntent.putExtra("isFromPizzaPassCampaign", categoryModel.isPizzaPassCampaign());
                        startActivityForResult(productPropertiesIntent, REQUEST_CODE_CAMPAIGN_PRODUCT_PROPERTIES);
                    }
                });
        campaignProductRecyclerView.addItemDecoration(new GridSpacesItemDecoration(2, 16, true));
        campaignProductRecyclerView.setAdapter(menuProductRecyclerAdapter);
    }

    private void getCampaignProducts(){
        DialogHelper.showLoadingDialog();
        Call<ResponseArray<MenuProductModel>> call = ApiService.apiInterface.getProductsByCategory(
                SessionHelper.getSelectedStore().getStoreName(),
                campaignModel.getCategoryId());
        call.enqueue(new Callback<ResponseArray<MenuProductModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<MenuProductModel>> call, Response<ResponseArray<MenuProductModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess())
                    fillAndNotifyProductList(response.body().getData());
                else
                    ApiErrorUtils.parseError(response);
            }

            @Override
            public void onFailure(Call<ResponseArray<MenuProductModel>> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void fillAndNotifyProductList(ArrayList<MenuProductModel> productList){
        MenuProductModel.checkNull(productList);
        menuProductList.clear();
        menuProductList.addAll(productList);
        sortProductsByName();
        menuProductRecyclerAdapter.notifyDataSetChanged();
    }

    private void sortProductsByName(){
        Collections.sort(menuProductList, new Comparator<MenuProductModel>() {
            @Override
            public int compare(MenuProductModel product1, MenuProductModel product2) {
                return  product1.getName().compareTo(product2.getName());
            }
        });
    }

}
