package com.gh.gamecenter.qa.editor

import android.app.Application
import androidx.annotation.Keep
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.UserEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.entity.ArticleEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

@Keep
class ArticleViewModel(application: Application, private val articleType: InsertArticleWrapperActivity.ArticleType) :
    ListViewModel<ArticleEntity, ArticleEntity>(application) {

    override fun provideDataObservable(page: Int): Observable<List<ArticleEntity>> {
        return if (articleType == InsertArticleWrapperActivity.ArticleType.MINE_ARTICLE) {
            RetrofitManager.getInstance().api.getMyArticle(UserManager.getInstance().userId, page)
        } else {
            RetrofitManager.getInstance().api.getCollectionCommunityArticle(UserManager.getInstance().userId, page)
        }
    }

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

    override fun filterData(list: MutableList<ArticleEntity>): MutableList<ArticleEntity> {
        var i = 0
        while (i < list.size) {
            val data = list[i]
            if (!data.active) {
                list.remove(data)
                i--
            }
            i++
        }

        if (articleType == InsertArticleWrapperActivity.ArticleType.MINE_ARTICLE) {
            val userInfoEntity = UserManager.getInstance().userInfoEntity
            list.forEach {
                it.user = UserEntity(
                    userInfoEntity?.icon, userInfoEntity?.name, userInfoEntity?.userId,
                    auth = userInfoEntity?.auth, badge = userInfoEntity?.badge
                )
            }
        }
        return list
    }

    class Factory(private val articleType: InsertArticleWrapperActivity.ArticleType) :
        ViewModelProvider.NewInstanceFactory() {

        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ArticleViewModel(HaloApp.getInstance().application, articleType) as T
        }
    }
}