package com.gh.gamecenter.qa.questions.invite

import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.common.util.ErrorHelper
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.qa.entity.InviteEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.HttpException

class QuestionsInviteViewModel(application: Application, var questionId: String?, var searchKey: String?) :
    ListViewModel<InviteEntity, InviteEntity>(application) {

    var invite = MutableLiveData<String>()
    var inviteError = MutableLiveData<String>()

    var forSearch: Boolean

    init {
        setOverLimitSize(1)
        forSearch = TextUtils.isEmpty(searchKey)
    }

    override fun provideDataObservable(page: Int): Observable<List<InviteEntity>> {
        return if (forSearch) {
            RetrofitManager.getInstance().api.getInviteExperts(questionId, HaloApp.getInstance().channel, page)
        } else {
            RetrofitManager.getInstance().api.getSearchInviteExperts(
                questionId,
                searchKey,
                HaloApp.getInstance().channel,
                page
            )
        }
    }

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

    fun invite(userId: String?) {
        val jsonObject = JSONObject()
        try {
            jsonObject.put("user_id", userId)
        } catch (e: JSONException) {
            e.printStackTrace()
        }

        val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
        RetrofitManager.getInstance().api
            .postInvite(body, questionId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    invite.postValue(userId)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    try {
                        val string = e?.response()?.errorBody()?.string()
                        val json = JSONObject(string)
                        if (e?.code() == 403 && "ALREADY ANSWERED" == json.getString("detail")) {
                            val data = json.getJSONObject("data")
                            inviteError.postValue(data.getString("answer_id"))
                            return
                        } else {
                            ErrorHelper.handleError(getApplication(), string, false)
                        }
                    } catch (e1: Exception) {
                        e1.printStackTrace()
                    }
                }
            })
    }

    class Factory(
        private val mApplication: Application,
        private val mQuestionId: String?,
        private val mSearchKey: String?
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return QuestionsInviteViewModel(mApplication, mQuestionId, mSearchKey) as T
        }
    }

}