package com.gh.gamecenter.qa.dialog

import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.entity.ForumEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.retrofit.service.ApiService
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class ChooseForumContainerViewModel(application: Application, val type: String, var searchKey: String) :
    ListViewModel<ForumEntity, ForumEntity>(application) {
    private val mApi: ApiService = RetrofitManager.getInstance().api

    init {
        if (type != ChooseForumContainerFragment.ChooseForumType.SEARCH.value) {
            load(LoadType.REFRESH)
        }
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<ForumEntity>> {
        return when (type) {
            ChooseForumContainerFragment.ChooseForumType.ATTENTION.value -> {
                mApi.getFollowsForum(UserManager.getInstance().userId)
            }
            ChooseForumContainerFragment.ChooseForumType.HOT.value -> {
                mApi.getHotForum(page)
            }
            else -> {
                mApi.searchBbs(searchKey, page)
            }
        }
    }

    fun setSearchKeyAndRefresh(searchKey: String) {
        this.searchKey = searchKey
        load(LoadType.REFRESH)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource<List<ForumEntity>>(mListLiveData) { mResultLiveData.postValue(it) }
    }

    class Factory(val type: String, val searchKey: String) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ChooseForumContainerViewModel(HaloApp.getInstance().application, type, searchKey) as T
        }
    }
}