package com.halo.assistant.fragment.user.auth

import android.annotation.SuppressLint
import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.entity.UserAuthEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserRepository
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.Single
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus

class UserAuthViewModel(application: Application): ListViewModel<UserAuthEntity, UserAuthEntity>(application) {
    private val mApi = RetrofitManager.getInstance().api
    private val mRepository by lazy {
        UserRepository.getInstance()
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<UserAuthEntity>>? = null

    @SuppressLint("CheckResult")
    override fun provideDataSingle(page: Int): Single<List<UserAuthEntity>> {
        return mApi.getUserAuthList(UserManager.getInstance().userId, true)
    }

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

    @SuppressLint("CheckResult")
    fun postUserAuth(id: String) {
        mApi.postUserAuth(UserManager.getInstance().userId, id)
            .compose(singleToMain())
            .subscribe(object :BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    load(LoadType.REFRESH)
                    mRepository.refreshUserInfo(null)
                    EventBus.getDefault().post(EBReuse("RefreshUserInfo"))
                    Utils.toast(getApplication(), "徽章佩戴成功！")
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    Utils.toast(getApplication(), "网络异常")
                }
            })
    }
}