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.AnswerEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import io.reactivex.Observable

@Keep
class AnswerViewModel(application: Application, private val answerType: InsertAnswerWrapperActivity.AnswerType) :
    ListViewModel<AnswerEntity, AnswerEntity>(application) {


    override fun provideDataObservable(page: Int): Observable<List<AnswerEntity>> {

        return if (answerType == InsertAnswerWrapperActivity.AnswerType.MINE_ANSWER) {
            RetrofitManager.getInstance().api.getMyAnswers(
                UserManager.getInstance().userId, page,
                HaloApp.getInstance().channel, Utils.getTime(getApplication())
            )
        } else {
            RetrofitManager.getInstance().api.getCollectionAnswer(UserManager.getInstance().userId, page)
        }
    }

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

    override fun filterData(list: MutableList<AnswerEntity>): MutableList<AnswerEntity> {
        var i = 0
        while (i < list.size) {
            val data = list[i]
            if (!data.active) {
                list.remove(data)
                i--
            }
            i++
        }
        if (answerType == InsertAnswerWrapperActivity.AnswerType.MINE_ANSWER) {
            list.forEach {
                val userInfoEntity = UserManager.getInstance().userInfoEntity
                it.user = UserEntity(
                    userInfoEntity?.icon, userInfoEntity?.name, userInfoEntity?.userId,
                    auth = userInfoEntity?.auth, badge = userInfoEntity?.badge
                )
            }
        }
        return list
    }

    class Factory(private val answerType: InsertAnswerWrapperActivity.AnswerType) :
        ViewModelProvider.NewInstanceFactory() {

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