package com.adealink.weparty.wallet.manager

import com.adealink.frame.base.Rlt
import com.adealink.frame.frame.BaseFrame
import com.adealink.weparty.App
import com.adealink.weparty.module.wallet.data.Currency
import com.adealink.weparty.wallet.datasource.remote.WalletHttpService
import kotlinx.coroutines.launch


val walletManager: IWalletManager by lazy { WalletManager() }

class WalletManager : BaseFrame<IWalletListener>(), IWalletManager {

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

    private var coin: Long = 0
    private var diamond: Long = 0
    private var bean: Long = 0

    override fun getWalletData() {
        launch {
            notifyCurrencyChanged()
        }
    }

    override fun refreshWalletDat() {
        launch {
            pullWalletData()
            notifyCurrencyChanged()
        }
    }

    override suspend fun pullWalletData(): Rlt<Map<Currency, Long>> {
        val rlt = walletHttpService.pullWallet()
        when (rlt) {
            is Rlt.Failed -> {
                return rlt
            }

            is Rlt.Success -> {
                this.coin = rlt.data.data?.coin ?: 0
                this.diamond = rlt.data.data?.diamond ?: 0
                return Rlt.Success(
                    mapOf(
                        Currency.COIN to this.coin,
                        Currency.DIAMOND to this.diamond
                    )
                )
            }
        }
    }

    private fun notifyCurrencyChanged() {
        dispatch {
            it.onCurrencyChanged(
                mapOf(
                    Currency.COIN to this.coin,
                    Currency.DIAMOND to this.diamond
                )
            )
        }
    }


}