package com.gh.gamecenter.cloudarchive

import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.entity.ArchiveEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.*
import retrofit2.HttpException
import java.io.IOException

open class BaseCloudArchiveViewModel(
    application: Application,
    private val mGameId: String,
    private var mConfigUrl: String
) : ListViewModel<ArchiveEntity, ArchiveEntity>(application) {
    private var mArchiveConfigStr = ""

    init {
        if (mConfigUrl.isEmpty()) {
            getArchiveConfigUrl()
        } else {
            getArchiveConfigString()
        }
    }

    // 通过url获取config字符串内容
    fun getArchiveConfigString(callback: ((String) -> Unit)? = null) {
        if (mArchiveConfigStr.isNotEmpty()) {
            callback?.invoke(mArchiveConfigStr)
        } else if (mConfigUrl.isNotEmpty()) {
            OkHttpClient().newCall(
                Request.Builder()
                    .url(mConfigUrl)
                    .build()
            )
                .enqueue(object : Callback {
                    override fun onResponse(call: Call, response: Response) {
                        mArchiveConfigStr = response.body?.string() ?: ""
                        callback?.invoke(mArchiveConfigStr)
                    }

                    override fun onFailure(call: Call, e: IOException) {
                        Utils.toast(getApplication(), "获取存档配置失败")
                        e.printStackTrace()
                    }
                })
        } else {
            Utils.toast(getApplication(), "获取存档配置失败")
        }
    }

    // 获取游戏存档配置url
    private fun getArchiveConfigUrl() {
        val map = mapOf(
            "game_ids" to listOf(mGameId)
        )
        RetrofitManager.getInstance().newApi.getGamesArchiveConfigs(map.toRequestBody())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : com.gh.gamecenter.common.retrofit.Response<List<ArchiveEntity>>() {
                override fun onResponse(response: List<ArchiveEntity>?) {
                    mConfigUrl = response?.find { it.gameId == mGameId }?.configUrl ?: return
                    getArchiveConfigString()
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    Utils.toast(getApplication(), "获取存档配置失败")
                }
            })
    }

    override fun provideDataObservable(page: Int): Observable<List<ArchiveEntity>>? = null

    override fun mergeResultLiveData() {}
}