package com.halo.assistant.fragment.user

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.common.util.ErrorHelper
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.login.entity.IdCardEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.HttpException

class ManuallyRealNameViewModel(application: Application) : AndroidViewModel(application) {

    var remoteImageUrl: String? = null

    var resultLiveData = MutableLiveData<Boolean>()
    var reviewLiveData = MutableLiveData<Boolean>()

    @SuppressLint("CheckResult")
    fun getCertificationReview() {
        RetrofitManager.getInstance().api.certificationReview
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    tryWithDefaultCatch {
                        val json = JSONObject(data.string())
                        val review = json.getBoolean("review")
                        reviewLiveData.postValue(review)
                    }
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    reviewLiveData.postValue(false)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun postCertificationReview(idCardEntity: IdCardEntity) {
        val userInfoEntity = UserInfoEntity()
        userInfoEntity.idCard = idCardEntity
        val body = RequestBody.create(
            MediaType.parse("application/json"), GsonUtils.toJson(userInfoEntity)
        )
        RetrofitManager.getInstance().api.postCertificationReview(body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody?>() {
                override fun onFailure(exception: Exception) {
                    ErrorHelper.handleError(
                        HaloApp.getInstance(),
                        (exception as? HttpException)?.response()?.errorBody()?.string()
                    )
                }

                override fun onSuccess(data: ResponseBody?) {
                    resultLiveData.postValue(true)
                }
            })
    }


}