package com.gh.gamecenter.forum.search

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.functions.BiFunction

class ForumOrUserSearchDefaultViewModel(application: Application) : AndroidViewModel(application) {

    val hotContentLiveData = MutableLiveData<List<SettingsEntity.Search.RankList>>()

    fun getForumSearchHotContent() {
        Observable.zip(
            getHotSearch(),
            getHotContent()
        ) { t1, t2 ->
            val dataList = arrayListOf<SettingsEntity.Search.RankList>()
            val forumRank = SettingsEntity.Search.RankList()
            forumRank.title = "热门论坛"
            val forumContent = arrayListOf<SettingsEntity.Search.RankList.RankContent>()
            t1.forEachIndexed { _, hotSearch ->
                val content = hotSearch.toRankContent()
                forumContent.add(content)
            }
            forumRank.content = forumContent
            val contentRank = SettingsEntity.Search.RankList()
            contentRank.title = "热门内容"
            t2.forEachIndexed { _, rankContent ->
                rankContent.name = rankContent.title
            }
            contentRank.content = t2
            dataList.add(forumRank)
            dataList.add(contentRank)
            dataList
        }.compose(observableToMain())
            .subscribe(object : Response<ArrayList<SettingsEntity.Search.RankList>>() {
                override fun onResponse(response: ArrayList<SettingsEntity.Search.RankList>?) {
                    super.onResponse(response)
                    hotContentLiveData.postValue(response)
                }

            })

    }


    private fun getHotSearch(): Observable<ArrayList<SettingsEntity.HotSearch>> {
        return RetrofitManager.getInstance().api
            .hotSearches
    }


    private fun getHotContent(): Observable<java.util.ArrayList<SettingsEntity.Search.RankList.RankContent>> {
        return RetrofitManager.getInstance().newApi
            .hotContent
    }
}