package ch.pizzapp.android.fragment.createOrder;

import android.os.Bundle;
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 com.google.android.gms.common.api.Api;

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.activity.BaseActivity;
import ch.pizzapp.android.activity.CreateOrderActivity;
import ch.pizzapp.android.adapter.recycler.PaymentMethodsRecyclerAdapter;
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.SessionHelper;
import ch.pizzapp.android.interfaces.RecyclerItemClickListener;
import ch.pizzapp.android.model.CheckCouponModel;
import ch.pizzapp.android.model.PaymentMethodModel;
import ch.pizzapp.android.model.PaymentMethodsResponseModel;
import ch.pizzapp.android.model.cart.CartInfoModel;
import ch.pizzapp.android.view.AppEditText;
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.couponCodePizzalinkEditText)
    AppEditText couponCodeAppEditText;

    @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;

    private ArrayList<PaymentMethodModel> paymentMethodList = new ArrayList<>();
    private PaymentMethodsRecyclerAdapter paymentMethodsRecyclerAdapter;
    private CheckCouponModel 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) getActivity();
        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(couponCodeAppEditText.isEmpty()){
                    createOrderActivity.setSelectedPaymentMethod(selectedPaymentMethod);
                    createOrderActivity.onNextClicked(FRAGMENT_NAME);
                }
                else {
                    createOrderActivity.setCouponCode(couponCodeAppEditText.getText());
                    checkCoupon();
                }



                break;
        }
    }

    private void initViews(){
        CreateOrderActivity createOrderActivity = (CreateOrderActivity) getActivity();
        if(createOrderActivity.getCouponCode() != null){
            couponCodeAppEditText.setText(createOrderActivity.getCouponCode());
        }
        initRecyclerView();
    }

    private void getPaymentMethods(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<PaymentMethodsResponseModel>> call = ApiService.apiInterface.getPaymentMethods(
                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) getActivity();
        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 checkCoupon(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<CheckCouponModel>> call =
                ApiService.apiInterface.checkCoupon(
                        ApiEndPoints.API_CHECK_COUPON + SessionHelper.getCustomerToken().getToken(),
                        couponCodeAppEditText.getText());
        call.enqueue(new Callback<ResponseObject<CheckCouponModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CheckCouponModel>> call, Response<ResponseObject<CheckCouponModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    couponModel = response.body().getData();
                    couponModel.checkNull();
                    if(couponModel.isActive()){
                        DialogHelper.showDialogWithPositiveButton(appName, BaseActivity.currentActivity, couponModel.getName());
                        getCartProducts();
                    }
                    else {
                        DialogHelper.hideLoadingDialog();
                        DialogHelper.showAlertDialog(BaseActivity.currentActivity, couponIsNotActiveText);
                    }
                }
                else {
                    DialogHelper.hideLoadingDialog();
                    ApiErrorUtils.parseError(response);
                }
            }

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

    private void getCartProducts(){
        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()){
                    CreateOrderActivity createOrderActivity = (CreateOrderActivity) getActivity();
                    createOrderActivity.setCartInfo(response.body().getData());
                    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();
            }
        });
    }

}