package com.gh.gamecenter.forum.search

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.feature.entity.AnswerEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class ForumContentSearchListViewModel(application: Application, val bbsId: String) :
    ListViewModel<AnswerEntity, AnswerEntity>(application) {
    var searchKey = ""
    var mSort = ""

    override fun provideDataObservable(page: Int): Observable<MutableList<AnswerEntity>>? {
        val map = hashMapOf("keyword" to searchKey, "sort" to mSort)
        if (bbsId.isNotEmpty()) {
            map["bbs_id"] = bbsId
        }
        return RetrofitManager.getInstance().api.searchForumContent(map, page)
    }

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

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

    fun updateSort(sort: String) {
        mSort = sort
        load(LoadType.REFRESH)
    }

    fun getLinkPageSize(): Int {
        return mCurLoadParams.loadOffset
    }

    class Factory(private val bbsId: String) : ViewModelProvider.NewInstanceFactory() {

        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ForumContentSearchListViewModel(HaloApp.getInstance().application, bbsId) as T
        }
    }
}