package ch.pizzapp.android.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzapp.android.R;
import ch.pizzapp.android.adapter.recycler.ProductCheckboxOptionsRecyclerAdapter;
import ch.pizzapp.android.adapter.recycler.ProductRadioOptionsRecyclerAdapter;
import ch.pizzapp.android.api.ApiConstants;
import ch.pizzapp.android.api.ApiEndPoints;
import ch.pizzapp.android.api.ApiErrorUtils;
import ch.pizzapp.android.api.ApiService;
import ch.pizzapp.android.api.ResponseObject;
import ch.pizzapp.android.helper.DialogHelper;
import ch.pizzapp.android.helper.ImageLoadHelper;
import ch.pizzapp.android.helper.PriceHelper;
import ch.pizzapp.android.helper.SessionHelper;
import ch.pizzapp.android.helper.SharedPrefsHelper;
import ch.pizzapp.android.helper.TextHelper;
import ch.pizzapp.android.interfaces.RecyclerItemClickListener;
import ch.pizzapp.android.model.AddProductToBasketResponseModel;
import ch.pizzapp.android.model.CampaignModel;
import ch.pizzapp.android.model.cart.CartInfoModel;
import ch.pizzapp.android.model.menu.MenuProductModel;
import ch.pizzapp.android.model.menu.MenuProductOptionModel;
import ch.pizzapp.android.model.menu.MenuProductOptionValueModel;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CampaignProductDetailsActivity extends BaseActivity {

    @BindView(R.id.closeImageView) ImageView closeImageView;
    @BindView(R.id.backIcon) ImageView backIcon;
    @BindView(R.id.productImageView) ImageView productImageView;
    @BindView(R.id.productNameTextView) TextView productNameTextView;
    @BindView(R.id.productPriceTextView) TextView productPriceTextView;
    @BindView(R.id.productDescriptionTextView) TextView productDescriptionTextView;
    @BindView(R.id.addToCartButton) Button addToCartButton;
    @BindView(R.id.radioRecyclerHeaderTextView) TextView radioRecyclerHeaderTextView;
    @BindView(R.id.radioRecyclerView) RecyclerView radioRecyclerView;
    @BindView(R.id.checkboxRecyclerHeaderTextView) TextView checkboxRecyclerHeaderTextView;
    @BindView(R.id.checkboxRecyclerView) RecyclerView checkboxRecyclerView;
    @BindView(R.id.increaseProductCountImageView) ImageView increaseProductCountImageView;
    @BindView(R.id.deccreaseProductCountImageView) ImageView deccreaseProductCountImageView;
    @BindView(R.id.productCountTextView) TextView productCountTextView;

    @BindString(R.string.no_options_selected_part) String noOptionsSelectedText;
    @BindString(R.string.cannot_use_campaign) String cannotUseCampaignText;

    private int productCount = 1;

    private MenuProductModel menuProductModel;

    private ArrayList<MenuProductOptionValueModel> productRadioOptionValueList = new ArrayList<>();
    private ArrayList<MenuProductOptionValueModel> productCheckboxOptionValueList = new ArrayList<>();
    private ProductRadioOptionsRecyclerAdapter productRadioOptionsRecyclerAdapter;
    private ProductCheckboxOptionsRecyclerAdapter productCheckboxOptionsRecyclerAdapter;
    private CampaignModel campaignModel;

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

    @OnClick({R.id.closeImageView,
            R.id.backIcon,
            R.id.addToCartButton})
    public void onCLick(View view){
        switch (view.getId()){
            case R.id.closeImageView:
            case R.id.backIcon:
                finish();
                break;
            case R.id.addToCartButton:
                if(checkFields()){
                    if(SessionHelper.isCustomerLoggedIn()){
                        if((campaignModel.getCode().equals(ApiConstants.CAMPAIGN_CODE_PIZZAPASS) && SessionHelper.isUserUsedPizzapassCampaign()) ||
                                (campaignModel.getCode().equals(ApiConstants.CAMPAIGN_CODE_CHAMPAGNE) && SessionHelper.isUserUsedChampagneCampaign())){
                            DialogHelper.showAlertDialog(BaseActivity.currentActivity, cannotUseCampaignText);
                        }
                        else {
                            addProductToCart();
                        }
                    }
                    else {
                        DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_shopping);
                    }
                }
                break;
        }
    }

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

        for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
            for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionModel.getOptionValueModelList()){
                menuProductOptionValueModel.setSelected(false);
            }
        }

        for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
            for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionModel.getOptionValueModelList()){
                if(menuProductOptionValueModel.getPrice().equals("0") || menuProductOptionValueModel.getPrice().equals("0.00")){

                    //checkbox
                    if(!(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                            menuProductOptionModel.getType().toLowerCase().equals("select"))){
                        menuProductOptionValueModel.setSelected(true);
                    }

                    //radio
                    else if(!isAnyOptionValueSelected(menuProductOptionModel.getOptionValueModelList())){
                        menuProductOptionValueModel.setSelected(true);
                    }

                }
            }
        }
    }

    private void getDataFromIntent(){
        menuProductModel = (MenuProductModel) getIntent().getSerializableExtra("menuProductModel");
        campaignModel = (CampaignModel) getIntent().getSerializableExtra("campaignModel");
    }
    private void initViews(){
        setFields();
        fillRadioAndCheckboxOptionLists();
        switch (menuProductModel.getProductOptionType()){
            case RADIO_AND_CHECKBOX:
                radioRecyclerView.setVisibility(View.VISIBLE);
                checkboxRecyclerView.setVisibility(View.VISIBLE);
                radioRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                checkboxRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                initRadioRecyclerView();
                initCheckboxRecyclerView();
                break;
            case RADIO:
                radioRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                radioRecyclerView.setVisibility(View.VISIBLE);
                checkboxRecyclerView.setVisibility(View.GONE);
                checkboxRecyclerHeaderTextView.setVisibility(View.GONE);
                initRadioRecyclerView();
                break;
            case CHECKBOX:
                radioRecyclerHeaderTextView.setVisibility(View.GONE);
                radioRecyclerView.setVisibility(View.GONE);
                checkboxRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                checkboxRecyclerView.setVisibility(View.VISIBLE);
                initCheckboxRecyclerView();
                break;
        }
    }

    public void setMenuProductModel(MenuProductModel menuProductModel){
        this.menuProductModel = menuProductModel;
    }

    private void initRadioRecyclerView(){
        radioRecyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(BaseActivity.currentActivity, 1);
        radioRecyclerView.setLayoutManager(gridLayoutManager);
        productRadioOptionsRecyclerAdapter = new ProductRadioOptionsRecyclerAdapter(productRadioOptionValueList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(!productRadioOptionValueList.get(position).isSelected()){
                    for(MenuProductOptionValueModel menuProductOptionValueModel : productRadioOptionValueList){
                        menuProductOptionValueModel.setSelected(false);
                    }
                    productRadioOptionValueList.get(position).setSelected(true);
                    productRadioOptionsRecyclerAdapter.notifyDataSetChanged();
                    productPriceTextView.setText(PriceHelper.calculatePriceAfterRadioOptionValueChanged(
                            productCount, menuProductModel, productRadioOptionValueList.get(position)));
                }
            }
        });
        radioRecyclerView.setAdapter(productRadioOptionsRecyclerAdapter);
    }

    private void initCheckboxRecyclerView(){
        checkboxRecyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(BaseActivity.currentActivity, 1);
        checkboxRecyclerView.setLayoutManager(gridLayoutManager);
        productCheckboxOptionsRecyclerAdapter = new ProductCheckboxOptionsRecyclerAdapter(productCheckboxOptionValueList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                productCheckboxOptionValueList.get(position).setSelected(
                        !productCheckboxOptionValueList.get(position).isSelected());
                productCheckboxOptionsRecyclerAdapter.notifyItemChanged(position);
                productPriceTextView.setText(
                        PriceHelper.calculatePriceAfterCheckboxOptionValueChanged(
                                productCount, menuProductModel, productCheckboxOptionValueList));
            }
        });
        checkboxRecyclerView.setAdapter(productCheckboxOptionsRecyclerAdapter);
    }

    private void setFields(){
        TextHelper.setTextFromHTML(productDescriptionTextView, menuProductModel.getDescription());
        ImageLoadHelper.loadImage(productImageView, menuProductModel.getImageURL());
        productNameTextView.setText(menuProductModel.getName());
        productPriceTextView.setText(PriceHelper.getPriceWithCurreny(menuProductModel.getPrice()));
        productPriceTextView.setText(PriceHelper.getPriceWithCurreny(menuProductModel.getPrice()));
    }

    private void fillRadioAndCheckboxOptionLists(){
        for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
            setSelectedPriceShowingOptions(menuProductOptionModel);

            if(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                    menuProductOptionModel.getType().toLowerCase().equals("select")){
                radioRecyclerHeaderTextView.setText(menuProductOptionModel.getName());
                productRadioOptionValueList.addAll(menuProductOptionModel.getOptionValueModelList());
            }
            else{
                checkboxRecyclerHeaderTextView.setText(menuProductOptionModel.getName());
                productCheckboxOptionValueList.addAll(menuProductOptionModel.getOptionValueModelList());
            }
        }
    }

    private void setSelectedPriceShowingOptions(MenuProductOptionModel menuProductOptionModel){
        for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionModel.getOptionValueModelList()){
            if(menuProductOptionValueModel.getPrice().equals("0") || menuProductOptionValueModel.getPrice().equals("0.00")){

                //checkbox
                if(!(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                        menuProductOptionModel.getType().toLowerCase().equals("select"))){
                    menuProductOptionValueModel.setSelected(true);
                }

                //radio
                else if(!isAnyOptionValueSelected(menuProductOptionModel.getOptionValueModelList())){
                    menuProductOptionValueModel.setSelected(true);
                }
            }
        }
    }

    private void addProductToCart(){

        DialogHelper.showLoadingDialog();
        Call<ResponseObject<AddProductToBasketResponseModel>> call =
                ApiService.apiInterface.addProductsToBasket(
                        ApiEndPoints.API_ADD_PRODUCTS_TO_BASKET + SessionHelper.getCustomerToken().getToken(),
                        getAddToCartRequestParams());
        call.enqueue(new Callback<ResponseObject<AddProductToBasketResponseModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<AddProductToBasketResponseModel>> call, Response<ResponseObject<AddProductToBasketResponseModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() && response.body().getData() != null){
                    if(response.body().isSuccess()){
                        DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, response.body().getData().getSuccessMessage());
                        getCartItemCount();
                    }
                    else
                        DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, response.body().getData().getErrorMessage());
                }
                else
                    ApiErrorUtils.parseError(response);
            }

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

    }

    private RequestBody getAddToCartRequestParams(){

        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("product_id", menuProductModel.getId());
        formBodyBuilder.add("quantity", String.valueOf(productCount));

        for(MenuProductOptionModel productOptionModel : menuProductModel.getProductOptionList()){
            ArrayList<String> selectedCheckboxOptionList = new ArrayList<>();
            for(MenuProductOptionValueModel productOptionValueModel : productOptionModel.getOptionValueModelList()){
                if(productOptionValueModel.isSelected()){
                    if(productOptionModel.getType().toLowerCase().equals("checkbox")){
                        selectedCheckboxOptionList.add(productOptionValueModel.getProductOptionValueId());
                    }
                    else {
                        String key = "option[" + productOptionModel.getProductOptionId() + "]";
                        formBodyBuilder.add(key, productOptionValueModel.getProductOptionValueId());
                    }
                }
            }
            if(productOptionModel.getType().toLowerCase().equals("checkbox")){
                for(int i = 0; i < selectedCheckboxOptionList.size(); i++){
                    String key = "option[" + productOptionModel.getProductOptionId() + "][" + String.valueOf(i) + "]";
                    formBodyBuilder.add(key, selectedCheckboxOptionList.get(i));
                }
            }
        }

        return formBodyBuilder.build();
    }


    private void getCartItemCount(){
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getCartTotalModel().getText()));
                    if(campaignModel.getCode().equals(ApiConstants.CAMPAIGN_CODE_PIZZAPASS)){
                        SessionHelper.setUserUsedPizzapassCampaign(true);
                    }
                    else if(campaignModel.getCode().equals(ApiConstants.CAMPAIGN_CODE_CHAMPAGNE)){
                        SessionHelper.setUserUsedChampagneCampaign(true);
                    }

                    /*
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.setCartItemCount();
                    */
                    setResult(RESULT_OK);

                    finish();

                }

            }

            @Override
            public void onFailure(Call<ResponseObject<CartInfoModel>> call, Throwable t) {

            }
        });
    }


    private boolean checkFields(){

        if(radioRecyclerView.getVisibility() == View.VISIBLE &&
                !isSelectedAtLeastOne(productRadioOptionValueList)){
            DialogHelper.showAlertDialog(BaseActivity.currentActivity,
                    radioRecyclerHeaderTextView.getText().toString() + " " + noOptionsSelectedText);
            return false;
        }

        if(checkboxRecyclerView.getVisibility() == View.VISIBLE &&
                !isSelectedAtLeastOne(productCheckboxOptionValueList)){
            DialogHelper.showAlertDialog(BaseActivity.currentActivity,
                    checkboxRecyclerHeaderTextView.getText().toString() + " " + noOptionsSelectedText);
            return false;
        }

        return true;
    }

    private boolean isSelectedAtLeastOne(ArrayList<MenuProductOptionValueModel> menuProductOptionValueModels){
        for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionValueModels){
            if(menuProductOptionValueModel.isSelected()){
                return true;
            }
        }
        return false;
    }

    private boolean isAnyOptionValueSelected(ArrayList<MenuProductOptionValueModel> menuProductOptionValueModels){
        for (MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionValueModels){
            if(menuProductOptionValueModel.isSelected()){
                return true;
            }
        }
        return false;
    }

}