package com.gh.gamecenter.forum.list

import android.annotation.SuppressLint
import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.ForumEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody

class ForumListViewModel(application: Application) : ListViewModel<ForumEntity, ForumEntity>(application) {

    private val mApi = RetrofitManager.getInstance().api
    var type = ForumListActivity.TYPE_FOLLOW

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

    override fun provideDataObservable(page: Int): Observable<MutableList<ForumEntity>> {
        return when (type) {
            ForumListActivity.TYPE_FOLLOW -> mApi.getFollowsForum(UserManager.getInstance().userId)
            ForumListActivity.TYPE_HOT -> mApi.getHotForum(page)
            ForumListActivity.TYPE_OFFICIAL -> mApi.getOfficialForum(page)
            else -> mApi.getHotForum(page)
        }
    }

    @SuppressLint("CheckResult")
    fun followForum(bbsId: String, onSuccess: () -> Unit) {
        mApi.followForum(bbsId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    onSuccess.invoke()
                }
            })
    }

    @SuppressLint("CheckResult")
    fun unFollowForum(bbsId: String, onSuccess: () -> Unit) {
        mApi.unFollowForum(bbsId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    onSuccess.invoke()
                }
            })
    }
}