package com.gh.gamecenter.energy.view

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.LoadParams
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.energy.HaloApp
import com.gh.gamecenter.energy.entity.CommodityEntity
import com.gh.gamecenter.energy.entity.Size
import com.gh.gamecenter.energy.retrofit.RetrofitManager
import io.reactivex.Single

class CommodityViewModel(application: Application, var categoryId: String, var entrance: String) :
    ListViewModel<CommodityEntity, CommodityEntity>(application) {

    init {
        if (entrance == "光能中心") {
            setOverLimitSize(11) // 光能中心的商品列表最多只展示10个
        }
    }

    var sortSize = Size()

    override fun provideDataObservable(page: Int) = null

    override fun provideDataSingle(page: Int): Single<List<CommodityEntity>> {
        return RetrofitManager.getInstance().api.getCommodities(
            getFilter(),
            page,
            if (entrance == "光能中心") 10
            else LoadParams.DEFAULT_PAGE_SIZE
        )
    }

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

    private fun getFilter(): String {
        return UrlFilterUtils.getFilterQuery(
            "category_id", categoryId,
            "min_energy", sortSize.min.toString(),
            "max_energy", sortSize.max.toString()
        )
    }

    class Factory(private val categoryId: String, private val entrance: String) :
        ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return CommodityViewModel(HaloApp.getInstance(), categoryId, entrance) as T
        }
    }
}