package com.gh.gamecenter.gamedetail.myrating

import android.app.Application
import com.gh.common.util.ErrorHelper
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.entity.ErrorEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.personalhome.rating.MyRating
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.HttpException

class MyRatingViewModel(application: Application) : ListViewModel<MyRating, MyRating>(application) {
    private val mApi = RetrofitManager.getInstance().api


    override fun provideDataObservable(page: Int): Observable<MutableList<MyRating>>? {
        return null
    }

    override fun provideDataSingle(page: Int): Single<MutableList<MyRating>> {
        return mApi.getMyRating(UserManager.getInstance().userId, page, "view:halo")
    }

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

    fun voteComment(gameId: String, commentId: String, callback: () -> Unit) {
        mApi.voteGameComment(gameId, commentId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    Utils.toast(getApplication(), "点赞成功")
                    callback.invoke()
                }

                override fun onFailure(e: HttpException?) {
                    val string = e?.response()?.errorBody()?.string()
                    val errorEntity = string?.toObject<ErrorEntity>()
                    if (errorEntity?.code == 403008) {
                        onResponse(null)
                        return
                    }
                    ErrorHelper.handleError(getApplication(), string)
                }
            })
    }

    fun unVoteComment(gameId: String, commentId: String, callback: () -> Unit) {
        mApi.unvoteGameComment(gameId, commentId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    Utils.toast(getApplication(), "取消点赞")
                    callback.invoke()
                }

                override fun onFailure(e: HttpException?) {
                    val string = e?.response()?.errorBody()?.string()
                    ErrorHelper.handleError(getApplication(), string)
                }
            })
    }
}