package com.gh.gamecenter.forum.moderator

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.gamecenter.entity.ApplyModeratorStatusEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.HttpException

class ApplyModeratorViewModel(application: Application, val bbsId: String) :
    AndroidViewModel(application) {

    val statusEntity = MutableLiveData<ApplyModeratorStatusEntity>()

    fun getModeratorsApplyStatus() {
        RetrofitManager.getInstance().api.getApplyModeratorStatus(bbsId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ApplyModeratorStatusEntity>() {
                override fun onResponse(response: ApplyModeratorStatusEntity?) {
                    super.onResponse(response)
                    statusEntity.postValue(response)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    statusEntity.postValue(null)
                }
            })
    }

    fun applyModerator(successCallback: (() -> Unit)?, failureCallback: (() -> Unit)?) {
        RetrofitManager.getInstance().api.postApplyModerator(bbsId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    successCallback?.invoke()
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    failureCallback?.invoke()
                }
            })
    }

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