package com.gh.gamecenter.gamedetail.cloudarchive

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.ArchiveEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Single

class CloudArchiveListViewModel(
    application: Application,
    private val mGameId: String,
    private var mKeyWord: String
) : ListViewModel<ArchiveEntity, ArchiveEntity>(application) {

    val refresh = MutableLiveData<Boolean>()
    private var mSortType = SortType.HOTTEST

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { list ->
            list.forEach { it.gameId = mGameId }
            mResultLiveData.postValue(list)
        }
    }

    override fun provideDataObservable(page: Int) = null

    override fun provideDataSingle(page: Int): Single<MutableList<ArchiveEntity>> {
        val map = hashMapOf<String, Any?>("sort" to getSortTypeFilter())
        if (mKeyWord.isNotBlank()) {
            map["keyword"] = mKeyWord
        }
        return RetrofitManager.getInstance().newApi.getGameArchives(mGameId, page, map)
    }

    fun getGameId() = mGameId

    fun update(sortType: SortType? = null, keyWord: String? = null) {
        when {
            sortType != null && sortType != mSortType -> {
                mSortType = sortType
                refresh.postValue(true)
            }

            !keyWord.isNullOrBlank() && keyWord != mKeyWord -> {
                mKeyWord = keyWord
                refresh.postValue(true)
            }
        }
    }

    fun getSortTypeValue() = mSortType.value

    private fun getSortTypeFilter(): String {
        return when (mSortType) {
            SortType.NEWEST -> "time.create:-1"
            else -> "hot:-1"
        }
    }

    enum class SortType(val value: String) {
        NEWEST("最新"),
        HOTTEST("最热")
    }

    class Factory(private val gameId: String, private val mKeyWord: String) : ViewModelProvider.NewInstanceFactory() {

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