package com.gh.gamecenter.qa.dialog

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.entity.ForumDetailEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp

class ChooseSectionViewModel(application: Application, val bbsId: String, val isModerator: Boolean) :
    AndroidViewModel(application) {
    private val mNewApi = RetrofitManager.getInstance().newApi
    val sectionListLiveData = MutableLiveData<List<ForumDetailEntity.Section>>()

    init {
        getSections()
    }

    private fun getSections() {
        mNewApi.getForumSections(bbsId)
            .compose(observableToMain())
            .subscribe(object : Response<List<ForumDetailEntity.Section>>() {
                override fun onResponse(response: List<ForumDetailEntity.Section>?) {
                    response?.run {
                        val validSectionList = ArrayList(this).apply {
                            removeAll { (it.permissions == "moderators" && !isModerator) || it.permissions == "nobody" }
                        }
                        sectionListLiveData.postValue(validSectionList)
                    }
                }
            })
    }

    class Factory(private val bbsId: String, private val isModerator: Boolean) :
        ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ChooseSectionViewModel(HaloApp.getInstance().application, bbsId, isModerator) as T
        }
    }
}