package com.gh.gamecenter.qa.article.detail

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.common.baselist.LoadStatus
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable

class ArticleDetailRelatedContentListViewModel(
    application: Application,
    private val articleId: String
) :
    ListViewModel<ArticleEntity, ArticleEntity>(application) {

    override fun provideDataObservable(page: Int): Observable<List<ArticleEntity>> {
        return RetrofitManager
            .getInstance()
            .newApi
            .getCommunityRelatedContentList(articleId)
    }

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

    override fun loadStatusControl(size: Int) {
        if (mCurLoadParams.loadOffset == LoadParams.DEFAULT_OFFSET) { // 初始化列表
            if (size == 0) {
                mLoadStatusLiveData.value = LoadStatus.INIT_EMPTY
            } else {
                mLoadStatusLiveData.value = LoadStatus.INIT_OVER
            }
        } else {
            when (size) {
                REQUEST_FAILURE_SIZE -> {
                    mLoadStatusLiveData.setValue(LoadStatus.LIST_FAILED)
                }
                0 -> {
                    mLoadStatusLiveData.setValue(LoadStatus.LIST_OVER)
                }
                else -> {
                    mLoadStatusLiveData.setValue(LoadStatus.LIST_LOADED)
                }
            }
        }

        if (size == REQUEST_FAILURE_SIZE) {
            mRetryParams = mCurLoadParams
        }
    }

    class Factory(
        private val application: Application,
        private val articleId: String = "",
    ) : ViewModelProvider.NewInstanceFactory() {

        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ArticleDetailRelatedContentListViewModel(
                application = application,
                articleId = articleId
            ) as T
        }
    }
}