package com.gh.gamecenter.category

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.common.exposure.ExposureUtils
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.common.view.ConfigFilterView
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.CategoryEntity
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.Single

class NewCategoryListViewModel(application: Application) : ListViewModel<GameEntity, GameEntity>(application) {

    var title = "" // 显示在 Toolbar 的标题
    var categoryTitle = "" // 跳转进来的分类的标题

    val refresh = MutableLiveData<Boolean>()

    var selectedCategory = CategoryEntity()

    var sortType = ConfigFilterView.SortType.RECOMMENDED
    private var mSortSize = SubjectSettingEntity.Size()

    override fun provideDataObservable(page: Int): Observable<List<GameEntity>>? {
        return null
    }

    override fun provideDataSingle(page: Int): Single<List<GameEntity>> {
        return RetrofitManager.getInstance()
            .api
            .getGamesInCategory(selectedCategory.id, getSortType(), getSortSize(), page)
    }

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

    fun changeSelectedCategory(category: CategoryEntity) {
        if (selectedCategory != category) {
            selectedCategory = category

            refresh.postValue(true)
        }
    }

    fun updateSortConfig(
        sortSize: SubjectSettingEntity.Size? = null,
        sortType: ConfigFilterView.SortType? = null
    ) {
        if (sortSize != null && sortSize != mSortSize) {
            mSortSize = sortSize
            refresh.postValue(true)
        } else if (sortType != null && sortType != this.sortType) {
            this.sortType = sortType
            refresh.postValue(true)
        }
    }

    private fun getSortSize(): String? {
        return UrlFilterUtils.getFilterQuery(
            "min_size", mSortSize.min.toString(),
            "max_size", mSortSize.max.toString()
        )
    }

    fun getSortType(): String? {
        return if (sortType == ConfigFilterView.SortType.RECOMMENDED) {
            "download:-1"
        } else {
            "publish:-1"
        }
    }

}