package com.gh.gamecenter.authorization

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.toJson
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.login.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.json.JSONArray
import org.json.JSONObject

/**
 * @author : liujiarui
 * date : 2023/4/13
 * description :
 */
class AuthorizationViewModel(application: Application) : AndroidViewModel(application) {
    private val mApi = RetrofitManager.getInstance().newApi

    @SuppressLint("CheckResult")
    fun getAccessToken(contentList: List<String>, onSuccess: (String) -> Unit, onFail: () -> Unit) {
        val jsonObject = JSONObject()
        val jsonArray = JSONArray()
        contentList.forEach {
            jsonArray.put(it)
        }
        jsonObject.put(EntranceConsts.KEY_CONTENT, jsonArray)
        val requestBody = jsonObject.toRequestBody()
        mApi.grant(requestBody)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    onSuccess(it.toJson())
                }, {
                    onFail()
                }
            )
    }
}