package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.annotation.SuppressLint
import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.livedata.NonStickyMutableLiveData
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

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

    val error = NonStickyMutableLiveData<Throwable>()

    override fun provideDataObservable(page: Int): Observable<List<GameEntity>> {
        return RetrofitManager.getInstance().newApi.serversSubscribedGameList
    }

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

    override fun loadStatusControl(size: Int) {
        when (size) {
            0 -> {
                mRetryParams = null
                mLoadStatusLiveData.setValue(LoadStatus.INIT_EMPTY)
            }
            REQUEST_FAILURE_SIZE -> {
                mRetryParams = mCurLoadParams
                mLoadStatusLiveData.setValue(LoadStatus.INIT_FAILED)
            }
            else -> {
                mRetryParams = null
                mLoadStatusLiveData.setValue(LoadStatus.INIT_OVER)
            }
        }
    }

    @SuppressLint("CheckResult")
    fun unsubscribeServer(gameId: String) {
        RetrofitManager.getInstance().newApi
            .unsubscribeServer(gameId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                val dataList = mListLiveData.value ?: return@subscribe
                val index = dataList.indexOfFirst { it.id == gameId }
                if (index != -1) {
                    dataList.removeAt(index)
                    mListLiveData.value = dataList
                }
            }, {
                error.postValue(it)
            })
    }
}