package com.gh.gamecenter.video.game

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.entity.GameVideoInfo
import com.gh.gamecenter.common.mvvm.Resource
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class GameVideoViewModel(application: Application, val gameId: String) : AndroidViewModel(application) {

    val gameViewInfo = MutableLiveData<Resource<GameVideoInfo>>()

    init {
        getGameVideoInfo()
    }

    @SuppressLint("CheckResult")
    private fun getGameVideoInfo() {
        RetrofitManager
            .getInstance()
            .api.getGameVideoInfo(gameId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<GameVideoInfo>() {
                override fun onSuccess(data: GameVideoInfo) {
                    gameViewInfo.postValue(Resource.success(data))
                }

                override fun onFailure(exception: Exception) {
                    gameViewInfo.postValue(Resource.error(null))
                }
            })
    }

    class Factory(
        private val mApplication: Application,
        private val gameId: String
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return GameVideoViewModel(mApplication, gameId) as T
        }
    }
}