package com.gh.gamecenter.forum.home

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.common.utils.createRequestBodyAny
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.ForumEntity
import com.gh.gamecenter.entity.ForumUnreadEntity
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.entity.ArticleEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.room.AppDatabase
import io.reactivex.Observable

class ForumArticleListViewModel(application: Application) : ListViewModel<ArticleEntity, ArticleEntity>(application) {

    private val mForumDao = AppDatabase.getInstance().forumDao()
    val recordForumsLiveData = MutableLiveData<Pair<List<ForumEntity>, Boolean>>()
    var recordForums = arrayListOf<ForumEntity>()
    var recordStatusForums = arrayListOf<ForumUnreadEntity>()
    var sort: String = "time.comment"//排序 time.edit 最新发布 time.comment 最新回复
    var videoList = arrayListOf<ForumVideoEntity>()

    init {
        setOverLimitSize(0)
        getRecordForums()
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<ArticleEntity>>? {
        return RetrofitManager.getInstance()
            .api.getForumRecommends(UrlFilterUtils.getFilterQuery(sort, "-1"), page)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { list ->

            videoList = ArrayList(list.map { it.transformForumVideoEntity() })

            mResultLiveData.postValue(list)
        }
    }

    @SuppressLint("CheckResult")
    fun getRecordForums() {
        mForumDao.getForum()
            .subscribe({
                it?.run {
                    if (it.isNotEmpty()) {
                        recordForums = ArrayList(it)
                        getForumUnreadStatus()
                    }
                }
            }, { })
    }

    @SuppressLint("CheckResult")
    fun getForumUnreadStatus(isFromRefresh: Boolean = true) {
        if (recordForums.isEmpty()) return

        if (!UserManager.getInstance().isLoggedIn) {
            recordForumsLiveData.postValue(Pair(recordForums, isFromRefresh))
            return
        }

        val requestMap = hashMapOf<String, Any>()
        recordStatusForums.clear()
        recordForums.forEach {
            recordStatusForums.add(it.transformUnreadEntity())
        }
        requestMap["bbs"] = recordStatusForums
        val body = requestMap.createRequestBodyAny()
        RetrofitManager.getInstance()
            .api
            .getForumUnreadStatus(body)
            .compose(singleToMain())
            .subscribe(object : BiResponse<List<ForumUnreadEntity>>() {

                override fun onSuccess(data: List<ForumUnreadEntity>) {
                    if (data.isNotEmpty() && data.size == recordForums.size) {
                        data.forEachIndexed { index, unreadEntity ->
                            recordForums[index].unread = unreadEntity.unread
                            recordStatusForums[index].unread = unreadEntity.unread
                        }
                    }
                    recordForumsLiveData.postValue(Pair(recordForums, isFromRefresh))
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    recordForumsLiveData.postValue(Pair(recordForums, isFromRefresh))
                }
            })
    }
}