package com.gh.gamecenter.gamecollection.hotlist

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.common.baselist.LoadStatus
import com.gh.gamecenter.entity.GamesCollectionEntity
import com.gh.gamecenter.gamecollection.square.GameCollectionListItemData
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class GameCollectionHotListViewModel(application: Application, private val mCollectionId: String) :
    ListViewModel<GamesCollectionEntity, GameCollectionListItemData>(application) {
    private val mApi = RetrofitManager.getInstance().api

    override fun provideDataObservable(page: Int): Observable<MutableList<GamesCollectionEntity>> {
        return mApi.getGameCollectionHotList(mCollectionId)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            var position = 0
            val itemDataList = ArrayList<GameCollectionListItemData>()
            for (item in it) {
                item.games = RegionSettingHelper.filterSimpleGame(item.games)
                itemDataList.add(
                    GameCollectionListItemData(
                        gameCollectionItem = item,
                        gameStartPosition = position,
                        isGameCollectionItem = true
                    )
                )
                position += if (item.count?.game!! > 2) 3 else if (item.games?.size == 0) 0 else item.count?.game ?: 0
            }
            mResultLiveData.postValue(itemDataList)
            mLoadStatusLiveData.postValue(LoadStatus.INIT_OVER)
        }
    }

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