package com.gh.common.exposure

import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.IExposureStateChangeListener
import com.gh.gamecenter.feature.exposure.RecyclerViewExposureHelper
import com.lightgame.utils.Utils

class DefaultExposureStateChangeListener : IExposureStateChangeListener {

    override fun onExposureStateChange(
        exposureEvent: ExposureEvent,
        position: Int,
        inExposure: Boolean
    ) {
        val exposureStatus = if (inExposure) "曝光中" else "结束曝光"

        val isCPMExposureEvent = exposureEvent.payload.miniGameType == Constants.WECHAT_MINI_GAME_CPM
        val isDSPExposureEvent = exposureEvent.payload.miniGameType == Constants.DSP_GAME

        Utils.log(
            RecyclerViewExposureHelper.TAG,
            "onExposureStateChange: 名称 ${exposureEvent.payload.gameName} 位置 $position, $exposureStatus"
        )

        // 如果是 CPM 曝光事件，且在曝光中，直接上报 CPM 曝光 (内部有做简单的去重处理，CPM 曝光追求一个及时上报，不用理会曝光时长)
        if (isCPMExposureEvent && inExposure) {
            Utils.log(
                RecyclerViewExposureHelper.TAG,
                "上报 CPM 曝光 ${exposureEvent.payload.gameName} ${exposureEvent.id}"
            )
            ExposureManager.logCPM(exposureEvent)
        } else if (isDSPExposureEvent && inExposure) {
            Utils.log(
                RecyclerViewExposureHelper.TAG,
                "上报 DSP 曝光 ${exposureEvent.payload.gameName} ${exposureEvent.id}"
            )
            ExposureManager.logDSP(exposureEvent)
        }

        if (!inExposure
            && System.currentTimeMillis() - exposureEvent.timeInMillisecond > DEFAULT_VALID_EXPOSURE_THRESHOLD
        ) {
            Utils.log(
                RecyclerViewExposureHelper.TAG,
                "上报曝光 ${exposureEvent.payload.gameName} ${exposureEvent.id}，是否为 CPM 小游戏 -> ${isCPMExposureEvent}，" +
                        "曝光时长为 ${System.currentTimeMillis() - exposureEvent.timeInMillisecond}ms"
            )

            // 标记当前 ExposureEvent 已经被使用过
            exposureEvent.markIsUsed()
            ExposureManager.log(exposureEvent)
        }
    }

    companion object {
        // 默认曝光有效时长
        const val DEFAULT_VALID_EXPOSURE_THRESHOLD = 1000L
    }

}