package co.pixelbeard.theanfieldwrap.buyTokens;

import android.content.Context;

import co.pixelbeard.theanfieldwrap.data.responses.GetWalletResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.networking.CallbackWrapper;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;

public class BuyTokensPresenter implements BuyTokensContract.Presenter {


    private BuyTokensContract.View mView;
    private DataRepository mRepo;
    private Context mContext;

    public BuyTokensPresenter(BuyTokensContract.View view, DataRepository repo, Context context) {
        if (view != null && repo != null) {
            this.mView = view;
            this.mRepo = repo;
            mContext = context;

            mView.setPresenter(this);
        }
    }


    @Override
    public void creditAccount(int value, String title, String purchaseToken) {

        if (mView != null && mView.checkConnection()) {
            mView.showLoader("Crediting your account");
            mRepo.creditUserAccount(value, title, purchaseToken).subscribe(new CallbackWrapper<GetWalletResponse>(mView) {
                @Override
                protected void onSuccess(GetWalletResponse getWalletResponse) {
                    if (mView != null) {
                        mView.consumeToken(purchaseToken);
                        PrefUtils.getInstance().putIntPref(PrefKey.TOKEN_BALANCE, getWalletResponse.getWallet().getBalance());
                        mView.goBack();
                    }
                }

                @Override
                protected void onSuccessFalse(GetWalletResponse getWalletResponse) {
                    if (mView != null) {
                        mView.showSingleButtonDialog("Error", getWalletResponse.getMessage());
                    }
                }
            });
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {

    }

    @Override
    public void clearUserData(Context context) {
        //Not needed
    }
}
