package com.gh.gamecenter.qa.questions.draft

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.feature.entity.QuestionDraftEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import okhttp3.ResponseBody
import retrofit2.HttpException

class QuestionDraftViewModel(application: Application) :
    ListViewModel<QuestionDraftEntity, QuestionDraftEntity>(application) {
    val deleteDraftSuccess = MutableLiveData<Pair<String, Boolean>>()
    private val api = RetrofitManager.getInstance().api

    override fun provideDataObservable(page: Int): Observable<MutableList<QuestionDraftEntity>> {
        return api.getQuestionDrafts(UserManager.getInstance().userId)
    }

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

    @SuppressLint("CheckResult")
    fun deleteDraft(draftId: String) {
        api.deleteQuestionDraft(UserManager.getInstance().userId, draftId)
            .compose(observableToMain())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    deleteDraftSuccess.postValue(Pair(draftId, true))
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    deleteDraftSuccess.postValue(Pair(draftId, false))
                }
            })

    }
}