package ch.pizzalemon.android.fragment.createOrder;

import android.os.Bundle;
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.EditText;

import java.util.ArrayList;
import java.util.HashMap;

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.CreateOrderActivity;
import ch.pizzalemon.android.adapter.recycler.PaymentMethodsRecyclerAdapter;
import ch.pizzalemon.android.api.ApiEndPoints;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseObject;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.CouponModel;
import ch.pizzalemon.android.model.CouponType;
import ch.pizzalemon.android.model.GeneralCouponModel;
import ch.pizzalemon.android.model.PersonalCouponModel;
import ch.pizzalemon.android.model.PaymentMethodModel;
import ch.pizzalemon.android.model.PaymentMethodsResponseModel;
import ch.pizzalemon.android.model.cart.CartInfoModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cimenmus on 17/10/2017.
 */

public class PaymentMethodFragment extends CreateOrderBaseFragment {

    @BindView(R.id.paymentMethodsRecyclerView) RecyclerView paymentMethodsRecyclerView;
    @BindView(R.id.couponCodeEditText) EditText couponCodeEditText;

    @BindString(R.string.app_name) String appName;
    @BindString(R.string.alert_choose_payment_method) String choosePaymentMethodText;
    @BindString(R.string.coupon_is_not_active) String couponIsNotActiveText;
    @BindString(R.string.coupon_used_dialog_title) String couponUsedDialogTitle;
    @BindString(R.string.coupon_used_dialog_message) String couponUsedDialogMessage;

    private ArrayList<PaymentMethodModel> paymentMethodList = new ArrayList<>();
    private PaymentMethodsRecyclerAdapter paymentMethodsRecyclerAdapter;
    private CouponModel couponModel;

    private PaymentMethodModel selectedPaymentMethod;

    public static final java.lang.String FRAGMENT_NAME = "paymentMethodFragment";

    public PaymentMethodFragment() {}

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

    @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_payment_method, container, false);
        ButterKnife.bind(this, view);
        initViews();
        getPaymentMethods();
        return view;
    }

    @OnClick({R.id.previousTextView, R.id.nextTextView})
    protected void onClick(View view){
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;
        switch (view.getId()){
            case R.id.previousTextView:
                createOrderActivity.onPreviousClicked(FRAGMENT_NAME);
                break;
            case R.id.nextTextView:

                if(selectedPaymentMethod == null){
                    DialogHelper.showAlertDialog(BaseActivity.currentActivity, choosePaymentMethodText);
                    break;
                }

                if(couponCodeEditText.getText().toString().isEmpty()){
                    SessionHelper.clearSelectedCoupon();
                    createOrderActivity.setSelectedPaymentMethod(selectedPaymentMethod);
                    createOrderActivity.onNextClicked(FRAGMENT_NAME);
                }
                else {
                    createOrderActivity.setCouponCode(couponCodeEditText.getText().toString());
                    checkPersonalCoupon();
                }
                break;
        }
    }

    private void initViews(){
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;
        if(createOrderActivity.getCouponCode() != null){
            couponCodeEditText.setText(createOrderActivity.getCouponCode());
        }
        initRecyclerView();
    }

    private void getPaymentMethods(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<PaymentMethodsResponseModel>> call = ApiService.apiInterface.getPaymentMethods(
                SessionHelper.getSelectedStore().getStoreName(),
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject<PaymentMethodsResponseModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<PaymentMethodsResponseModel>> call, Response<ResponseObject<PaymentMethodsResponseModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    fillAndNotifyAdapter(response.body().getData().getPaymentMethodsList());
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void fillAndNotifyAdapter(ArrayList<PaymentMethodModel> paymentMethodModels){
        PaymentMethodModel.checkNull(paymentMethodModels);

        for(PaymentMethodModel paymentMethodModel : paymentMethodModels){
            if(paymentMethodModel.getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.APPLE_PAY){
                paymentMethodModels.remove(paymentMethodModel);
                break;
            }
        }

        for(PaymentMethodModel paymentMethodModel : paymentMethodModels){
            if(paymentMethodModel.getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.ANDROID_PAY){
                paymentMethodModels.remove(paymentMethodModel);
                break;
            }
        }

        for(PaymentMethodModel paymentMethodModel : paymentMethodModels){
            if(paymentMethodModel.getPaymentMethodType() == PaymentMethodModel.PaymentMethodType.TWINT){
                paymentMethodModels.remove(paymentMethodModel);
                break;
            }
        }

        /*
        // dummy //
        PaymentMethodModel paypal = new PaymentMethodModel();
        paypal.setCode(ApiConstants.PAYMENT_METHOD_CODE_PAYPAL);
        paypal.setTitle("PAYPAL");
        paypal.setSortOrder("0");
        paymentMethodModels.add(paypal);
        */

        /*
        // dummy //
        PaymentMethodModel androidPay = new PaymentMethodModel();
        androidPay.setCode(ApiConstants.PAYMENT_METHOD_CODE_ANDROID_PAY);
        androidPay.setTitle("Android Pay");
        androidPay.setSortOrder("0");
        paymentMethodModels.add(androidPay);
        */


        PaymentMethodModel.sort(paymentMethodModels);
        paymentMethodList.clear();
        paymentMethodList.addAll(paymentMethodModels);
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;
        if(paymentMethodList.size() != 0){

            if(createOrderActivity.getSelectedPaymentMethod() == null){
                paymentMethodList.get(0).setSelected(true);
                selectedPaymentMethod = paymentMethodList.get(0);
            }
            else {
                for(PaymentMethodModel paymentMethodModel : paymentMethodModels){
                    if(paymentMethodModel.getCode().equals(createOrderActivity.getSelectedPaymentMethod().getCode())){
                        paymentMethodModel.setSelected(true);
                        selectedPaymentMethod = paymentMethodModel;
                        break;
                    }
                }
            }

        }
        createOrderActivity.setPaymentMethodList(paymentMethodList);
        paymentMethodsRecyclerAdapter.notifyDataSetChanged();
    }

    private void initRecyclerView(){
        paymentMethodsRecyclerAdapter = new PaymentMethodsRecyclerAdapter(paymentMethodList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                for (PaymentMethodModel paymentMethodModel : paymentMethodList){
                    paymentMethodModel.setSelected(false);
                }
                paymentMethodList.get(position).setSelected(true);
                selectedPaymentMethod = paymentMethodList.get(position);
                paymentMethodsRecyclerAdapter.notifyDataSetChanged();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(BaseActivity.currentActivity);
        paymentMethodsRecyclerView.setLayoutManager(layoutManager);
        paymentMethodsRecyclerView.setAdapter(paymentMethodsRecyclerAdapter);
    }

    private void checkPersonalCoupon(){
        Call<ResponseObject<PersonalCouponModel>> call =
                ApiService.apiInterface.checkPersonalCoupon(
                        "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_CHECK_PERSONAL_COUPON + SessionHelper.getCustomerToken().getToken(),
                        couponCodeEditText.getText().toString());
        call.enqueue(new Callback<ResponseObject<PersonalCouponModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<PersonalCouponModel>> call, Response<ResponseObject<PersonalCouponModel>> response) {
                if(response.isSuccessful()){

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

                        couponModel = response.body().getData();
                        couponModel.setStoreName(SessionHelper.getSelectedStore().getStoreName());
                        if(couponModel.isActive()){
                            SessionHelper.saveSelectedCoupon(couponModel);
                            DialogHelper.showDialogWithPositiveButton(
                                    couponUsedDialogTitle,
                                    BaseActivity.currentActivity,
                                    couponUsedDialogMessage);
                            getCartProducts();
                        }
                        else {
                            checkGeneralCoupon();
                            //DialogHelper.hideLoadingDialog();
                            //ApiErrorUtils.parseError(response);
                        }
                    }
                    else {
                        checkGeneralCoupon();
                        //DialogHelper.hideLoadingDialog();
                        //ApiErrorUtils.parseError(response);
                    }
                }
                else {
                    checkGeneralCoupon();
                    //DialogHelper.hideLoadingDialog();
                    //ApiErrorUtils.parseError(response);
                }
            }

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

    private void checkGeneralCoupon(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<GeneralCouponModel>> call =
                ApiService.apiInterface.checkGeneralCoupon(
                        "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_CHECK_GENERAL_COUPON + SessionHelper.getCustomerToken().getToken(),
                        couponCodeEditText.getText().toString());
        call.enqueue(new Callback<ResponseObject<GeneralCouponModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<GeneralCouponModel>> call, Response<ResponseObject<GeneralCouponModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    couponModel = response.body().getData();
                    couponModel.setStoreName(SessionHelper.getSelectedStore().getStoreName());

                    String couponName = "";
                    if(couponModel instanceof GeneralCouponModel){
                        couponName = ((GeneralCouponModel) couponModel).getName();
                    }

                    if(couponModel.isActive()){
                        SessionHelper.saveSelectedCoupon(couponModel);
                        DialogHelper.showDialogWithPositiveButton(
                                couponUsedDialogTitle,
                                BaseActivity.currentActivity,
                                couponUsedDialogMessage);
                        getCartProducts();
                    }
                    else {
                        DialogHelper.hideLoadingDialog();
                        DialogHelper.showAlertDialog(BaseActivity.currentActivity, couponIsNotActiveText);
                    }
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

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

        HashMap<String, Object> params = new HashMap<>();
        if(couponModel != null){
            if(couponModel.getCouponType() == CouponType.PERSONAL){
                params.put("voucher", couponModel.getCode());
            }
            else if(couponModel.getCouponType() == CouponType.GENERAL){
                params.put("coupon", couponModel.getCode());
            }
        }

        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) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    CreateOrderActivity createOrderActivity = (CreateOrderActivity) BaseActivity.currentActivity;
                    CartInfoModel cartInfoModel = response.body().getData();
                    cartInfoModel.checkNull();
                    createOrderActivity.setCartInfoSafeForCampaigns(cartInfoModel);
                    createOrderActivity.setSelectedPaymentMethod(selectedPaymentMethod);
                    createOrderActivity.onNextClicked(FRAGMENT_NAME);
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

}