package com.adealink.weparty.wallet.recharge.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.App
import com.adealink.weparty.module.wallet.data.Currency
import com.adealink.weparty.wallet.datasource.remote.WalletHttpService
import com.adealink.weparty.wallet.recharge.data.RechargeConfigData
import com.adealink.weparty.wallet.recharge.data.RechargeConfigReq
import com.adealink.weparty.wallet.recharge.data.RechargeItemData
import kotlinx.coroutines.launch

class RechargeViewModel : BaseViewModel() {

    private val walletHttpService by lazy {
        App.instance.networkService.getHttpService(WalletHttpService::class.java)
    }

    private val rechargeList = mutableListOf<RechargeItemData>()
    private var selectedItem: RechargeItemData? = null
    val rechargeListLD = MutableLiveData<List<RechargeItemData>>()
    fun pullRechargeList(currency: Currency) {
        viewModelScope.launch {
            val rlt = walletHttpService.rechargeConfig(RechargeConfigReq(currency = currency.type))
            when (rlt) {
                is Rlt.Failed -> {
                    rechargeList.clear()
                    rechargeList.addAll(EMPTY_RECHARGE_LIST)
                    rechargeListLD.send(rechargeList)
                }

                is Rlt.Success -> {
                    rechargeList.clear()
                    rechargeList.addAll(rlt.data.data?.items?.map {
                        RechargeItemData(it)
                    } ?: EMPTY_RECHARGE_LIST)
                    rechargeListLD.send(rechargeList)
                }
            }
        }
    }

    fun getSelectedItem(): RechargeItemData? {
        return selectedItem
    }

    fun selectItem(item: RechargeItemData) {
        for (data in rechargeList) {
            data.selected = data == item
            if (data.selected) {
                selectedItem = data
            }
        }
        rechargeListLD.send(rechargeList)
    }


    companion object {
        private val EMPTY_RECHARGE_LIST = listOf(
            RechargeItemData(RechargeConfigData("", 0, 0.0)),
            RechargeItemData(RechargeConfigData("", 0, 0.0)),
            RechargeItemData(RechargeConfigData("", 0, 0.0)),
            RechargeItemData(RechargeConfigData("", 0, 0.0)),
            RechargeItemData(RechargeConfigData("", 0, 0.0)),
            RechargeItemData(RechargeConfigData("", 0, 0.0))
        )
    }
}