package com.gh.gamecenter.personalhome.home.game

import android.annotation.SuppressLint
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.Response

class UserGameViewModel(application: Application, private val mUserId: String) : AndroidViewModel(application) {

    var playedGameCount = MutableLiveData<Int>()

    init {
        getUserPlayedGameCount()
    }

    @SuppressLint("CheckResult")
    fun getUserPlayedGameCount() {
        RetrofitManager.getInstance()
            .api.getPlayedGamesCount(mUserId, Utils.getTime(getApplication()))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<Response<ResponseBody>>() {
                override fun onSuccess(data: retrofit2.Response<ResponseBody>) {
                    val countContent = data.headers().get("Total")
                    playedGameCount.postValue(if (TextUtils.isEmpty(countContent)) 0 else countContent?.toInt() ?: 0)
                }
            })
    }


    class Factory(private val userId: String) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return UserGameViewModel(HaloApp.getInstance().application, userId) as T
        }
    }
}