package com.gh.common.util

import android.annotation.SuppressLint
import android.text.TextUtils
import com.gh.common.constant.Config
import com.gh.gamecenter.common.entity.IdfaData
import com.gh.gamecenter.common.pagelevel.IPageLevelProvider
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.tracker.IBusiness
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.entity.StartupAdEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.schedulers.Schedulers

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"

    // 广告标识 https://jira.shanqu.cc/browse/GHZSCY-7041
    private var idfa = ""

    @SuppressLint("CheckResult")
    @JvmStatic
    fun getIdfa(versionName: String, channel: String) {
        RetrofitManager.getInstance().newApi.getIdfa(versionName, channel)
            .subscribeOn(Schedulers.io())
            .subscribe(object : BiResponse<IdfaData>() {
                override fun onSuccess(data: IdfaData) {
                    idfa = data.AD

                    SensorsBridge.trackGetAdTag(data.AD)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)

                    SensorsBridge.trackGetAdTag("")
                }
            })
    }

    fun getIdfaString() : String {
        return idfa
    }

    /**
     * 记录广告游戏填充
     */
    fun reportAdRequest(exposureEvent: ExposureEvent) {
        val payload = exposureEvent.payload
        NewFlatLogUtils.logAdRequest(
            pageLevel = payload.pageLevel ?: "",
            currentPageCode = payload.currentPageCode ?: "",
            currentPageId = payload.currentPageId ?: "",
            gameName = payload.gameName ?: "",
            gameId = payload.gameId ?: "",
            moduleType = payload.moduleType ?: "",
            moduleStyle = payload.moduleStyle ?: "",
            moduleName = payload.moduleName ?: "",
            moduleId = payload.moduleId ?: "",
            searchContent = payload.searchContent ?: "",
            sequence = payload.sequence ?: -1,
            outerSequence = payload.outerSequence ?: -1,
            adGroupId = payload.adGroupId ?: "",
        )
    }

    /**
     * 记录广告游戏填充
     */
    fun reportAdRequest(gameEntity: GameEntity) {
        val currentActivity = CurrentActivityHolder.getCurrentActivity()
        val subPageCode = gameEntity.subPageCode
        val subPageId = gameEntity.subPageId

        val currentActivitySimpleName = if (currentActivity != null) currentActivity::class.simpleName else "unknown"
        val businessId = if (currentActivity is IBusiness) currentActivity.getBusinessId() else null

        var currentPageCode = currentActivitySimpleName
        var currentPageId = businessId?.first

        // 子页面的 pageCode 添加到主页面后， pageId 优先级高于主页面 pageId
        if (!subPageCode.isNullOrEmpty()) {
            currentPageCode = "$currentActivitySimpleName-$subPageCode"
            if (!subPageId.isNullOrEmpty()) {
                currentPageId = subPageId
            }
        }

        var pageLevelString: String? = gameEntity.pageLevelString

        if (TextUtils.isEmpty(pageLevelString)) {
            val pageLevelProvider = currentActivity as? IPageLevelProvider
            pageLevelString = pageLevelProvider?.getPageLevel()?.toFormattedString()
        }

        NewFlatLogUtils.logAdRequest(
            pageLevel = pageLevelString ?: "",
            currentPageCode = currentPageCode ?: "",
            currentPageId = currentPageId ?: "",
            gameName = gameEntity.name ?: "",
            gameId = gameEntity.id,
            moduleStyle = gameEntity.customPageTrackData?.modulePattern ?: "",
            moduleType = gameEntity.customPageTrackData?.moduleType ?: "",
            moduleName = gameEntity.customPageTrackData?.linkContentName ?: "",
            moduleId = gameEntity.customPageTrackData?.linkContentId ?: "",
            searchContent = "",
            sequence = gameEntity.sequence ?: -1,
            outerSequence = gameEntity.outerSequence ?: -1,
            adGroupId = gameEntity.adGroupId,
        )
    }


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

    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
    }
}