package com.gh.gamecenter.game.upload

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.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.common.retrofit.ApiResponse
import com.google.gson.JsonObject
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import okhttp3.ResponseBody

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

    val upLoadSuccess = MutableLiveData<Boolean>()
    val uploadGameTips = MutableLiveData<String>()

    //上传游戏
    fun uploadGames(body: RequestBody) {
        RetrofitManager.getInstance()
            .api.uploadGames(UserManager.getInstance().userId, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    upLoadSuccess.postValue(true)
                }

                override fun onApiFailure(e: ApiResponse<ResponseBody>?) {
                    super.onApiFailure(e)
                    upLoadSuccess.postValue(false)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getUploadGamesTips() {
        RetrofitManager.getInstance()
            .api.uploadGamesTips()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<JsonObject>() {
                override fun onSuccess(data: JsonObject) {
                    val tips = data.get("text").asString
                    if (!tips.isNullOrEmpty()) {
                        uploadGameTips.postValue(tips)
                    }
                }
            })
    }

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

}