package com.gh.gamecenter.home.custom

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.gh.common.filter.RegionSettingHelper
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.entity.HomeSubSlide
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.retrofit.service.ApiService
import com.lightgame.utils.Utils
import io.reactivex.Observable
import retrofit2.HttpException

class CommonContentCollectionUseCase private constructor(
    private val api: ApiService
) {
    var refreshCount = 0
    private var slideDiscoveryGamesPage = -1

    private val _slideDiscoveryCardGames = MutableLiveData<List<GameEntity>>()
    val slideDiscoveryCardGames: LiveData<List<GameEntity>> = _slideDiscoveryCardGames
    fun loadSlideDiscoverCardGames(homeSubSlide: HomeSubSlide) {
        if (slideDiscoveryGamesPage != homeSubSlide.repeatCount || slideDiscoveryCardGames.value == null) {
            val paramsMap = if (SPUtils.getBoolean(Constants.SP_DISCOVER_FORCE_REFRESH)) {
                mapOf("page_size" to 3, "view" to "sub_slide", "refresh" to "true")
            } else {
                mapOf("page_size" to 3, "view" to "sub_slide")
            }
            api.getDiscoveryGames(1, paramsMap)
                .map { it.games }
                .map(RegionSettingHelper.filterGame)
                .compose(observableToMain())
                .subscribe(object : Response<List<GameEntity>>() {
                    override fun onResponse(response: List<GameEntity>?) {
                        response?.let {
                            SPUtils.setBoolean(Constants.SP_DISCOVER_FORCE_REFRESH, false)
                            _slideDiscoveryCardGames.postValue(it)
                            slideDiscoveryGamesPage = homeSubSlide.repeatCount
                        }
                    }
                })
        }
    }

    companion object {
        fun newInstance() =
            CommonContentCollectionUseCase(
                RetrofitManager.getInstance().api
            )
    }
}