package com.gh.gamecenter.gamecollection.publish

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.entity.GameCollectionCoverEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import retrofit2.HttpException

class ChooseGameCollectionDefaultCoverViewModel(application: Application) : AndroidViewModel(application) {

    private val mApi = RetrofitManager.getInstance().api
    val coverListLivedata = MutableLiveData<List<GameCollectionCoverEntity>?>()

    init {
        getRandomCover()
    }

    fun getRandomCover() {
        mApi.randomCover.compose(observableToMain())
            .subscribe(object : Response<List<GameCollectionCoverEntity>>() {
                override fun onResponse(response: List<GameCollectionCoverEntity>?) {
                    super.onResponse(response)
                    coverListLivedata.postValue(response)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    ToastUtils.showToast("加载失败")
                }
            })

    }


    class Factory : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ChooseGameCollectionDefaultCoverViewModel(HaloApp.getInstance().application) as T
        }
    }
}