package com.gh.gamecenter.minigame.wechat

import android.annotation.SuppressLint
import androidx.lifecycle.LiveData
import com.gh.gamecenter.common.livedata.NonStickyMutableLiveData
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.feature.entity.GameEntity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * 微信小游戏CPM-网域层
 */
class WGameSubjectCPMListUseCase(
    private val repository: WGameSubjectCPMListRepository = WGameSubjectCPMListRepository()
) {

    /**
     * 微信专题CPM请求记录，用于避免重复请求，以专题ID作为Key
     */
    private val requestKeyList = mutableListOf<String>()

    /**
     * 微信小游戏CPM列表，这里的LiveData充当类似于EventBus的角色，因此使用NonStickyMutableLiveData
     */
    private val _wechatMiniGameCPMListLiveData = NonStickyMutableLiveData<Pair<String, List<GameEntity>>>()
    val wechatMiniGameCPMListLiveData: LiveData<Pair<String, List<GameEntity>>> = _wechatMiniGameCPMListLiveData

    @SuppressLint("CheckResult")
    fun getWechatMiniGameCPMList(subjectId: String?, minimumSize: Int, onlyFee: Boolean) {
        if (subjectId.isNullOrEmpty() || requestKeyList.contains(subjectId)) {
            return
        }

        requestKeyList.add(subjectId)
        repository.getColumn(null, 1, null, null, null, null, minimumSize, onlyFee)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<GameEntity>>() {
                override fun onSuccess(data: List<GameEntity>) {
                    requestKeyList.remove(subjectId)
                    _wechatMiniGameCPMListLiveData.value = subjectId to data
                }
            })
    }
}