package com.gh.gamecenter.history

import android.app.Application
import com.gh.gamecenter.core.AppExecutor
import com.gh.common.history.HistoryDatabase
import com.gh.common.history.HistoryHelper
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.entity.GameEntity
import io.reactivex.Observable
import io.reactivex.Single

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

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

    override fun provideDataSingle(page: Int): Single<List<GameEntity>> {
        return if (page > 5) {
            Single.create { it.onSuccess(arrayListOf()) }
        } else {
            HistoryDatabase.instance.gameDao().getGamesWithOffset(20, (page - 1) * 20).map {
                val gameEntityList = arrayListOf<GameEntity>()
                for (history in it) {
                    gameEntityList.add(history.convertHistoryGameEntityToGameEntity())
                }
                gameEntityList
            }
        }
    }

    fun removeHistory(gameEntity: GameEntity) {
        mResultLiveData.value?.let {
            HistoryHelper.deleteGameEntity(gameEntity.id)

            it.remove(gameEntity)
            if (it.size == 0) {
                AppExecutor.uiExecutor.executeWithDelay({ load(LoadType.REFRESH) }, 100)
            } else {
                mResultLiveData.postValue(it)
            }
        }
    }

    fun removeHistories(ids: List<String>) {
        mResultLiveData.value?.let { datas ->
            ids.forEach { id ->
                HistoryHelper.deleteGameEntity(id)
                val entity = datas.find { it.id == id }
                datas.remove(entity)
            }
            if (datas.size == 0) {
                AppExecutor.uiExecutor.executeWithDelay({ load(LoadType.REFRESH) }, 100)
            } else {
                mResultLiveData.postValue(datas)
            }
        }

    }

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

}