package com.gh.common.util

import com.gh.common.constant.Config
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.entity.NewApiSettingsEntity
import com.gh.gamecenter.entity.StartupAdEntity
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp

object AdHelper {

    // 搜索为空/求版本/意见反馈-功能收录/发现/模拟器游戏
    const val LOCATION_SEARCH_EMPTY = "search_empty"
    const val LOCATION_GAME_REQUEST_VERSION = "game_request_version"
    const val LOCATION_SUGGESTION_FUNCTION = "suggestion_function"
    const val LOCATION_SIMULATOR_GAME = "simulator_game"

    @JvmStatic
    fun getStartUpAd(): StartupAdEntity? {
        return Config.getNewApiSettingsEntity()?.startAd
    }

    @JvmStatic
    fun getStartUp(): StartupAdEntity? {
        return Config.getNewApiSettingsEntity()?.startup
    }

    @JvmStatic
    fun prefetchStartUpAd(settingsEntity: NewApiSettingsEntity) {
        if (settingsEntity.startAd != null && !settingsEntity.startAd?.img.isNullOrEmpty()) {
            val screenWidth = DisplayUtils.getScreenWidth()
            val transformedUrl = ImageUtils.getTransformedUrl(settingsEntity.startAd?.img, screenWidth) ?: return
            ImageUtils.prefetchToDiskCache(transformedUrl)
        }
    }

    fun getSettingAdCache() {
        RetrofitManager.getInstance().newApi
            .getSettingAdCache(HaloApp.getInstance().channel)
            .compose(observableToMain())
            .subscribe(object : Response<NewApiSettingsEntity>() {
                override fun onResponse(response: NewApiSettingsEntity?) {
                    super.onResponse(response)
                    val settings = Config.getNewApiSettingsEntity()
                    if (settings != null) {
                        settings.startAd = response?.startAd
                        Config.updateNewApiSettings(settings)
                        if (response != null) {
                            prefetchStartUpAd(response)
                        }
                    }
                }
            })
    }

    fun getAd(location: String): SettingsEntity.AD? {
        val adList = Config.getSettings()?.adList ?: return null

        for (ad in adList) {
            if (ad.location == location) return ad
        }
        return null
    }

    fun getAdForLocation(location: String): SettingsEntity.AD? {
        val adList = Config.getSettings()?.adList ?: return null

        var result: SettingsEntity.AD? = null
        run outside@{
            for (ad in adList) {
                if (ad.location == location) {
                    result = ad
                    return@outside
                }
            }
        }

        return result
    }
}