package com.gh.gamecenter.gamecollection.hotlist

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.entity.GameCollectionListEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import retrofit2.HttpException

class GameCollectionHotListWrapperViewModel(application: Application) : AndroidViewModel(application) {
    private val mApi = RetrofitManager.getInstance().api

    val hotListTabListLiveData = MutableLiveData<List<GameCollectionListEntity>?>()

    init {
        getGameCollectionHotListTab()
    }

    fun getGameCollectionHotListTab() {
        mApi.gameCollectionHotListTab
            .compose(observableToMain())
            .subscribe(object : Response<List<GameCollectionListEntity>>() {
                override fun onResponse(response: List<GameCollectionListEntity>?) {
                    super.onResponse(response)
                    response?.let {
                        val hotListTabList = ArrayList<GameCollectionListEntity>()
                        it.forEachIndexed { index, entity ->
                            hotListTabList.add(entity.apply {
                                position = index + 1
                            })
                        }
                        hotListTabListLiveData.postValue(hotListTabList)
                    }
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    hotListTabListLiveData.postValue(null)
                }
            })
    }
}