package ch.pizzalink.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.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.HashMap;
import java.util.Locale;

import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalink.android.R;
import ch.pizzalink.android.activity.BaseActivity;
import ch.pizzalink.android.activity.CreateOrderActivity;
import ch.pizzalink.android.activity.MainActivity;
import ch.pizzalink.android.adapter.recycler.CartRecyclerAdapter;
import ch.pizzalink.android.api.ApiEndPoints;
import ch.pizzalink.android.api.ApiErrorUtils;
import ch.pizzalink.android.api.ApiService;
import ch.pizzalink.android.api.ResponseObject;
import ch.pizzalink.android.helper.DialogHelper;
import ch.pizzalink.android.helper.PriceHelper;
import ch.pizzalink.android.helper.SessionHelper;
import ch.pizzalink.android.helper.SharedPrefsHelper;
import ch.pizzalink.android.interfaces.RecyclerItemClickListener;
import ch.pizzalink.android.model.RemoveProductFromCartResponseModel;
import ch.pizzalink.android.model.cart.CartInfoModel;
import ch.pizzalink.android.model.cart.CartProductModel;
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;


    @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 CartInfoModel cartInfoModel;
    private ArrayList<CartProductModel> cartProductList = new ArrayList<>();
    private CartRecyclerAdapter cartRecyclerAdapter;

    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();
        getCartProducts();
        return view;
    }

    @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:
                Intent continueCartIntent = new Intent(BaseActivity.currentActivity, CreateOrderActivity.class);
                continueCartIntent.putExtra("cartInfoModel", cartInfoModel);
                startActivity(continueCartIntent);
                break;
        }
    }

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

    private void getCartProducts(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                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()){
                    cartInfoModel = response.body().getData();
                    setCartTotalFields();
                    fillAndNotifyAdapter();
                }
                else
                    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.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) getActivity();
                    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());
        cartRecyclerAdapter.notifyDataSetChanged();
        setCartLayoutsVisibility();
    }

    private void setCartTotalFields(){
        cartTotalLabelTextView.setText(cartInfoModel.getTotals().get(0).getTitle().toUpperCase(Locale.GERMAN));
        cartProductTotalTextView.setText(PriceHelper.roundFractions(cartInfoModel.getTotals().get(0).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(
                        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) getActivity();
                            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.getCustomerToken().getToken());
        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.showOneButtonDialogWithCallback(productRemovedFromCartText, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                            SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getTotals().get(0).getText()));
                            MainActivity mainActivity = (MainActivity) getActivity();
                            mainActivity.setCartItemCount();
                            mainActivity.reopenCartFragment();
                        }
                    });

                }

            }

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

            }
        });
    }
}
