package com.gh.gamecenter.gamecollection.mine

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.GamesCollectionEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import okhttp3.ResponseBody
import retrofit2.HttpException

class MyGameCollectionViewModel(application: Application) :
    ListViewModel<GamesCollectionEntity, GamesCollectionEntity>(application) {
    private val mApi = RetrofitManager.getInstance().api
    val deleteLiveData = MutableLiveData<GamesCollectionEntity>()
    val publishLiveData = MutableLiveData<GamesCollectionEntity>()
    override fun provideDataObservable(page: Int): Observable<MutableList<GamesCollectionEntity>>? {
        return mApi.getGameCollectionList(UserManager.getInstance().userId, page)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { mResultLiveData.postValue(it) }
    }

    fun deleteGameCollection(entity: GamesCollectionEntity) {
        mApi.deleteGameCollection(entity.id)
            .compose(observableToMain())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    deleteLiveData.postValue(entity)
                }

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

    fun publishGameCollection(entity: GamesCollectionEntity) {
        mApi.publishGameCollection(entity.id)
            .compose(observableToMain())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    publishLiveData.postValue(entity)
                }

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