package com.gh.gamecenter.gamecollection.choose

import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.common.filter.RegionSettingHelper
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.TagStyleEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable
import io.reactivex.Single

class HotGameListViewModel(
    application: Application,
    var subjectData: SubjectData,
) : ListViewModel<GameEntity, GameEntity>(application) {
    private val mApi = RetrofitManager.getInstance().api
    override fun provideDataObservable(page: Int): Observable<MutableList<GameEntity>>? = null

    override fun provideDataSingle(page: Int): Single<MutableList<GameEntity>> {
        return mApi.getColumn(
            subjectData.subjectId,
            subjectData.sort,
            subjectData.filter.ifEmpty { "type:全部" },
            "",
            "",
            page)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            val gameSubjectData = subjectData.toGameSubjectData()
            val useUpdateTagStyle = subjectData.tagType == "update"

            val filterGame = RegionSettingHelper.filterGame(it)
            val iterator = filterGame.iterator()
            while (iterator.hasNext()) {
                val game = iterator.next()
                if (game.id.isEmpty()) {
                    iterator.remove()
                    continue
                }
                game.isAdData = subjectData.isAdData
                game.subjectData = gameSubjectData
                if (useUpdateTagStyle) {
                    game.tagStyle.clear()
                    game.tagStyle.add(
                        TagStyleEntity(
                            id = "local_generated",
                            name = TimeUtils.getFormatTime(game.updateTime, "MM-dd") + " 更新",
                            color = "1383EB",
                            background = "E8F3FF",
                            column = "1383EB"
                        )
                    )
                }
            }
            mResultLiveData.postValue(filterGame)
        }
    }

    class Factory(private val subjectData: SubjectData) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return HotGameListViewModel(HaloApp.getInstance(), subjectData) as T
        }
    }
}