package kr.co.vividnext.sodalive.mypage.can.charge.iap

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.Purchase
import com.orhanobut.logger.Logger
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.mypage.can.CanRepository

class CanChargeIapViewModel(private val repository: CanRepository) : BaseViewModel() {
    private val _toastLiveData = MutableLiveData<String?>()
    val toastLiveData: LiveData<String?>
        get() = _toastLiveData

    private var _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean>
        get() = _isLoading

    fun chargeCan(
        title: String,
        selectedProductDetails: ProductDetails,
        purchase: Purchase,
        onSuccess: (Int) -> Unit
    ) {
        val productId = purchase.products.firstOrNull()
        if (productId != null) {
            _isLoading.value = true

            compositeDisposable.add(
                repository.googleChargeCan(
                    request = GoogleChargeRequest(
                        title = title,
                        chargeCan = selectedProductDetails.description.toInt(),
                        price = (
                            selectedProductDetails.oneTimePurchaseOfferDetails?.priceAmountMicros
                                ?: 0L).toDouble() / 1000000,
                        currencyCode = selectedProductDetails.oneTimePurchaseOfferDetails?.priceCurrencyCode
                            ?: "KRW",
                        productId = purchase.products[0],
                        purchaseToken = purchase.purchaseToken
                    ),
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            _isLoading.value = false
                            if (it.success) {
                                onSuccess(selectedProductDetails.description.toInt())
                            } else {
                                if (it.message != null) {
                                    _toastLiveData.value = it.message
                                } else {
                                    _toastLiveData.value = "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                }
                            }
                        },
                        {
                            _isLoading.value = false
                            it.message?.let { message -> Logger.e(message) }
                            _toastLiveData.value = "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                        }
                    )
            )
        } else {
            _toastLiveData.value = "구매를 하지 못했습니다.\n고객센터로 문의해 주시기 바랍니다."
        }
    }

    fun showToast(message: String) {
        _toastLiveData.value = message
    }

    fun setLoading(isLoading: Boolean) {
        _isLoading.value = isLoading
    }
}
