package com.gh.gamecenter.feedback.view.help

import android.annotation.SuppressLint
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.mvvm.Resource
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.feedback.entity.HelpCategoryEntity
import com.gh.gamecenter.feedback.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

class HelpContainerViewModel(
    application: Application,
    val qaId: String?,
    val qaCollectionId: String?
) : AndroidViewModel(application) {
    private val mApi = RetrofitManager.getInstance().api

    /**
     *  Pair first: 是否显示内容（true：显示，false：隐藏）
     *  Pair second: 是否显示搜索框（true：显示，false：隐藏）
     */
    val configLiveData = MutableLiveData<Pair<Boolean?, Boolean?>>()

    val categoryLiveData = MutableLiveData<Resource<List<HelpCategoryEntity>>>()

    init {
        initData()
    }

    fun initData() {
        if (!qaId.isNullOrEmpty()) {
            getQaConfig()
        } else {
            getHelpCategory()
        }
    }

    @SuppressLint("CheckResult")
    fun getHelpCategory() {
        mApi.getHelpCategory()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<HelpCategoryEntity>>() {
                override fun onSuccess(data: List<HelpCategoryEntity>) {
                    categoryLiveData.postValue(Resource.success(data))
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    val httpException = if (exception is HttpException) {
                        exception
                    } else null
                    categoryLiveData.postValue(Resource.error(httpException))
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getQaConfig() {
        mApi.getQaConfig(qaId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    val jsonObject = JSONObject(data.string())
                    val active = jsonObject.getBoolean("active")
                    val search = jsonObject.getBoolean("search")
                    configLiveData.postValue(Pair(active, search))
                }

                override fun onFailure(exception: Exception) {
                    configLiveData.postValue(null)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getQaCollection() {
        mApi.getQaCollection(qaCollectionId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<HelpCategoryEntity>>() {
                override fun onSuccess(data: List<HelpCategoryEntity>) {
                    categoryLiveData.postValue(Resource.success(data))
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    val httpException = if (exception is HttpException) {
                        exception
                    } else null
                    categoryLiveData.postValue(Resource.error(httpException))
                }
            })
    }

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