package com.gh.common.util

import android.annotation.SuppressLint
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.WechatConfigEntity
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.common.utils.createRequestBody
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.common.utils.toJson
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import okhttp3.ResponseBody
import retrofit2.HttpException

object WechatBindHelper {

    @JvmStatic
    @SuppressLint("CheckResult")
    fun getWechatConfig(callback: ((WechatConfigEntity) -> Unit)? = null) {
        if (!UserManager.getInstance().isLoggedIn) return
        RetrofitManager.getInstance()
            .newApi
            .wechatConfig
            .compose(singleToMain())
            .subscribe(object : BiResponse<WechatConfigEntity>() {
                override fun onSuccess(data: WechatConfigEntity) {
                    SPUtils.setString(Constants.SP_WECHAT_CONFIG, data.toJson())
                    callback?.invoke(data)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun bindWechat(wechatLoginInfoMap: Map<String, String>, callback: BiCallback<Boolean, Boolean>) {
        RetrofitManager.getInstance()
            .newApi
            .postBindWechat(wechatLoginInfoMap.createRequestBody())
            .compose(singleToMain())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    callback.onFirst(true)
                    getWechatConfig()
                }

                override fun onFailure(exception: Exception) {
                    callback.onSecond(true)
                    if (exception is HttpException) {
                        ErrorHelper.handleError(
                            HaloApp.getInstance().application,
                            exception.response().errorBody()?.string()
                        )
                    }
                }
            })
    }
}