package ch.pizzalemon.android.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

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

import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.activity.CampaignProductListActivity;
import ch.pizzalemon.android.activity.CreateOrderActivity;
import ch.pizzalemon.android.activity.MainActivity;
import ch.pizzalemon.android.adapter.recycler.CartRecyclerAdapter;
import ch.pizzalemon.android.api.ApiEndPoints;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseArray;
import ch.pizzalemon.android.api.ResponseObject;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.PriceHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.CampaignModel;
import ch.pizzalemon.android.model.RemoveProductFromCartResponseModel;
import ch.pizzalemon.android.model.cart.CartInfoModel;
import ch.pizzalemon.android.model.cart.CartProductModel;
import ch.pizzalemon.android.model.menu.MenuProductModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cimenmus on 18/09/2017.
 */

public class CartFragment extends BaseFragment {

    @BindView(R.id.cartFragmentMainLayout) RelativeLayout cartFragmentMainLayout;
    @BindView(R.id.noProductsOnCartTextView) TextView noProductsOnCartTextView;
    @BindView(R.id.cartRecyclerView) RecyclerView cartRecyclerView;
    @BindView(R.id.cartInfoLayout) LinearLayout cartInfoLayout;
    @BindView(R.id.cartTotalLabelTextView) TextView cartTotalLabelTextView;
    @BindView(R.id.cartProductTotalTextView) TextView cartProductTotalTextView;
    @BindView(R.id.continueCartButton) Button continueCartButton;
    @BindView(R.id.clearCartButton) Button clearCartButton;

    @BindString(R.string.bottom_nav_menu_item_cart) String fragmentTitle;
    @BindString(R.string.alert_remove_prdocut_from_cart) String removeProdcutFromCartAlert;
    @BindString(R.string.product_removed_from_cart) String productRemovedFromCartText;
    @BindString(R.string.alert_clear_cart) String clearCartAlertText;
    @BindString(R.string.minimum_order_price_alert_part_1) String minimumOrderPriceAlertPart1Text;
    @BindString(R.string.minimum_order_price_alert_part_2) String minimumOrderPriceAlertPart2Text;
    @BindString(R.string.something_went_wrong) String genericErrorText;

    @BindColor(R.color.actvity_default_background_color_1) int grayColor;
    @BindColor(R.color.white) int whiteColor;

    public static final java.lang.String FRAGMENT_NAME = "cartFragment";
    private int REQUEST_CODE_CAMPAIGN_PRODUCT_LIST = 7847;
    private String pizzaPassCampaignCategoryId = "";

    private CartInfoModel cartInfoModel;
    private ArrayList<CartProductModel> cartProductList = new ArrayList<>();
    private CartRecyclerAdapter cartRecyclerAdapter;
    private ArrayList<MenuProductModel> pizzaPassCampaignProductList = new ArrayList<>();

    public CartFragment() {}

    public static CartFragment newInstance() {
        return new CartFragment();
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        ButterKnife.bind(this, view);
        initViews();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getCartProducts();
    }

    /*
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_CAMPAIGN_PRODUCT_LIST && resultCode == RESULT_OK){
            BaseActivity.setCurrentActivity(createOrderActivity);
            getCartProducts();
        }
    }
    */

    @OnClick({R.id.clearCartButton, R.id.continueCartButton})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.clearCartButton:
                DialogHelper.showTwoButtonsDialog(BaseActivity.currentActivity, clearCartAlertText,
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                clearCart();
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        });
                break;
            case R.id.continueCartButton:

                // without minimum price control for store. minimum price is contorlled by addOrder2() service.
                if(!pizzaPassCampaignCategoryId.isEmpty()){
                    getCampaignProductsForPizzaPassOnContinueButtonClicked();
                }
                else {
                    openCreateOrderActivity();
                }
                break;

                // with minimum price control for store
                /*
                Double storeMinimumPrice = PriceHelper.stringToDouble(SessionHelper.getSelectedStore().getMinimumPrice());
                Double cartCurrentPrice = PriceHelper.stringToDouble(PriceHelper.removeCurrencyFromPrice(cartInfoModel.getCartTotalModel().getText()));

                if(cartCurrentPrice >=  storeMinimumPrice){

                    if(!pizzaPassCampaignCategoryId.isEmpty()){
                        getCampaignProductsForPizzaPassOnContinueButtonClicked();
                    }
                    else {
                        openCreateOrderActivity();
                    }

                }
                else {
                    String dialogText =
                            new StringBuilder()
                                    .append(minimumOrderPriceAlertPart1Text)
                                    .append(" ")
                                    .append(SessionHelper.getSelectedStore().getMinimumPrice())
                                    .append(" ")
                                    .append(minimumOrderPriceAlertPart2Text)
                                    .toString();

                    DialogHelper.showAlertDialog(
                            BaseActivity.currentActivity,
                            dialogText);
                }
                break;
                */

        }
    }

    private void initViews(){
        setPizzalinkToolbarFields(false, fragmentTitle);
        initRecyclerView();
    }

    private void getCartProducts(){
        DialogHelper.showLoadingDialog();
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
                */

        HashMap<String, Object> params = new HashMap<>();
        SessionHelper.addCouponCodeToRequestParamsIfNeeded(params);

        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                params);

        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    cartInfoModel = response.body().getData();
                    cartInfoModel.checkNull();
                    SharedPrefsHelper.setCartItemCount(cartInfoModel.getProducts().size());
                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(cartInfoModel.getCartTotalModel().getText()));
                    MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
                    mainActivity.updateBadge();
                    mainActivity.setCartTotalLayoutVisibility(false);
                    setCartTotalFields();
                    fillAndNotifyAdapter();

                    if(cartInfoModel.getProducts().isEmpty()){
                        DialogHelper.hideLoadingDialog();
                    }
                    else {
                        checkPizzaPassCampaign();
                    }
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void clearCart(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject> call = ApiService.apiInterface.clearCart(
                SessionHelper.getSelectedStore().getStoreName(),
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() && response.body().isSuccess()){
                    cartProductList.clear();
                    cartRecyclerAdapter.notifyDataSetChanged();
                    setCartLayoutsVisibility();
                    SharedPrefsHelper.setCartItemCount(0);
                    SharedPrefsHelper.setCartTotalPrice("0");
                    MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
                    mainActivity.setCartItemCount();
                }

                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void fillAndNotifyAdapter(){
        CartProductModel.checkNull(cartInfoModel.getProducts());
        cartProductList.clear();
        cartProductList.addAll(cartInfoModel.getProducts());
        sortCartProducts();
        cartRecyclerAdapter.notifyDataSetChanged();
        setCartLayoutsVisibility();
    }

    private void setCartTotalFields(){
        cartTotalLabelTextView.setText(cartInfoModel.getCartTotalModel().getTitle().toUpperCase(Locale.GERMAN));
        cartProductTotalTextView.setText(PriceHelper.roundFractions(cartInfoModel.getCartTotalModel().getText()));
    }

    private void initRecyclerView(){
        cartRecyclerAdapter = new CartRecyclerAdapter(cartProductList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                DialogHelper.showTwoButtonsDialog(BaseActivity.currentActivity, removeProdcutFromCartAlert,
                        new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                                removeProductFromCart(position);
                            }
                        }, new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        });
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(BaseActivity.currentActivity);
        cartRecyclerView.setLayoutManager(layoutManager);
        cartRecyclerView.setAdapter(cartRecyclerAdapter);
    }

    private void setCartLayoutsVisibility(){
        if(cartProductList.size() > 0){
            noProductsOnCartTextView.setVisibility(View.GONE);
            //cartFragmentMainLayout.setBackgroundColor(grayColor);
            cartRecyclerView.setVisibility(View.VISIBLE);
            cartInfoLayout.setVisibility(View.VISIBLE);
        }
        else {
            cartRecyclerView.setVisibility(View.GONE);
            cartInfoLayout.setVisibility(View.GONE);
            //cartFragmentMainLayout.setBackgroundColor(whiteColor);
            noProductsOnCartTextView.setVisibility(View.VISIBLE);
        }
    }

    private void removeProductFromCart(final int position){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<RemoveProductFromCartResponseModel>> call =
                ApiService.apiInterface.removeProductFromCart(
                        "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_REMOVE_RPODUCT_FORM_CART + SessionHelper.getCustomerToken().getToken(),
                        getRemoveProductFromCartRequestParams(cartProductList.get(position).getCartId()));
        call.enqueue(new Callback<ResponseObject<RemoveProductFromCartResponseModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<RemoveProductFromCartResponseModel>> call, Response<ResponseObject<RemoveProductFromCartResponseModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    cartProductList.remove(position);
                    getCartItemCount();
                    /*
                    DialogHelper.showOneButtonDialogWithCallback(productRemovedFromCartText, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            SharedPrefsHelper.setCartItemCount(cartProductList.size());
                            MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
                            mainActivity.setCartItemCount();
                            mainActivity.reopenCartFragment();
                        }
                    });
                    */
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private HashMap<String, Object> getRemoveProductFromCartRequestParams(String cartProductId){
        HashMap<String, Object> params = new HashMap<>();
        params.put("key", cartProductId);
        return params;
    }

    private void getCartItemCount(){
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
                */

        HashMap<String, Object> params = new HashMap<>();
        SessionHelper.addCouponCodeToRequestParamsIfNeeded(params);

        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                params);

        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, final Response<ResponseObject<CartInfoModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){

                    DialogHelper.showOneButtonDialogWithDismissListener(
                            productRemovedFromCartText,
                            new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialogInterface) {
                                    SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getCartTotalModel().getText()));
                                    MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
                                    mainActivity.setCartItemCount();
                                    mainActivity.reopenCartFragment();
                                }
                            }
                    );

                    if(!pizzaPassCampaignProductList.isEmpty()){
                        cartInfoModel.setPizzaPassCampaignUsed(
                                isBasketContainsCampaignProduct(
                                        pizzaPassCampaignProductList));
                    }

                }

            }

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

            }
        });
    }

    private void sortCartProducts(){

        ArrayList<CartProductModel> tempCartProductList = new ArrayList<>();

        // find margherita products
        ArrayList<CartProductModel> margheritaPizzaCartProductModelList = new ArrayList<>();
        for(CartProductModel cartProductModel: cartProductList){
            if (cartProductModel.getName().toLowerCase().equals("margherita")){
                margheritaPizzaCartProductModelList.add(cartProductModel);
            }
        }

        // remove margherita products from cartProductList
        if(!margheritaPizzaCartProductModelList.isEmpty()){
            cartProductList.removeAll(margheritaPizzaCartProductModelList);

        }

        // sort cartProductList alphebetically
        Collections.sort(cartProductList, new Comparator<CartProductModel>() {
            @Override
            public int compare(CartProductModel cpm1, CartProductModel cpm2) {
                return cpm1.getName().compareTo(cpm2.getName());
            }
        });

        // add margherita products to temp tempCartProductList
        if(!margheritaPizzaCartProductModelList.isEmpty()){
            tempCartProductList.addAll(margheritaPizzaCartProductModelList);
        }

        tempCartProductList.addAll(cartProductList);
        cartProductList.clear();
        cartProductList.addAll(tempCartProductList);

    }

    private void checkPizzaPassCampaign(){
        ApiService
                .apiInterface
                .checkPizzaPassCampaign(
                        SessionHelper.getSelectedStore().getStoreName(),
                        SessionHelper.getCustomerToken().getToken())
                .enqueue(new Callback<ResponseObject<CampaignModel>>() {
                    @Override
                    public void onResponse(Call<ResponseObject<CampaignModel>> call, Response<ResponseObject<CampaignModel>> response) {
                        DialogHelper.hideLoadingDialog();
                        if(response.isSuccessful() &&
                                response.body() != null){

                            if(response.body().isSuccess()){

                                if(response.body().getData() == null){
                                    DialogHelper.showAlertDialog(BaseActivity.currentActivity, genericErrorText);
                                }
                                else {
                                    pizzaPassCampaignCategoryId = response.body().getData().getCategoryId();
                                    getCampaignProducts(response.body().getData());
                                }
                            }

                        }
                        else{
                            ApiErrorUtils.parseError(response);
                        }
                    }

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

    private void showPizzaPassCampaignDialog(final CampaignModel campaignModel){
        DialogHelper.showTwoButtonsDialog(
                campaignModel.getName(),
                campaignModel.getDescription(),
                R.string.accept_campaign,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Intent campaignIntent = new Intent(BaseActivity.currentActivity, CampaignProductListActivity.class);
                        campaignIntent.putExtra("campaignModel", campaignModel);
                        startActivityForResult(campaignIntent, REQUEST_CODE_CAMPAIGN_PRODUCT_LIST);
                    }
                },
                R.string.decline_campaign,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    }
                },
                false
        );
    }

    private void getCampaignProducts(final CampaignModel campaignModel){
        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()) {
                    if(!isBasketContainsCampaignProduct(response.body().getData())){
                        showPizzaPassCampaignDialog(campaignModel);
                    }
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void getCampaignProductsForPizzaPassOnContinueButtonClicked(){

       DialogHelper.showLoadingDialog();

        Call<ResponseArray<MenuProductModel>> call = ApiService.apiInterface.getProductsByCategory(
                SessionHelper.getSelectedStore().getStoreName(),
                pizzaPassCampaignCategoryId);
        call.enqueue(new Callback<ResponseArray<MenuProductModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<MenuProductModel>> call, Response<ResponseArray<MenuProductModel>> response) {

                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()) {

                    pizzaPassCampaignProductList.clear();
                    pizzaPassCampaignProductList.addAll(response.body().getData());
                    cartInfoModel.setPizzaPassCampaignUsed(isBasketContainsCampaignProduct(response.body().getData()));

                    DialogHelper.hideLoadingDialog();
                    openCreateOrderActivity();
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private boolean isBasketContainsCampaignProduct(ArrayList<MenuProductModel> campaignProductsList){

        boolean isContains = false;

        outerLoop:for(CartProductModel cartProductModel : cartProductList) {
            for(MenuProductModel campaignProductModel : campaignProductsList){
                if(cartProductModel.getProductId().equals(campaignProductModel.getId())){
                    isContains = true;
                    break outerLoop;
                }
            }
        }

        return isContains;
    }

    private void openCreateOrderActivity(){
        Intent continueCartIntent = new Intent(BaseActivity.currentActivity, CreateOrderActivity.class);
        continueCartIntent.putExtra("cartInfoModel", cartInfoModel);
        startActivity(continueCartIntent);
    }

}
