package com.rgt.superr.business.ads

import com.rgt.superr.BuildConfig
import com.rgt.superr.bean.config.AdConfigBean
import com.rgt.superr.utils.AppPreferences
import com.rgt.superr.utils.KotlinExt.toFormatTime4
import com.rgt.superr.utils.LogEx


/**
 * 控制广告计数与判断显示条件
 *
 */
object LimitUtils {
    const val NUM_NATIVE_DISPLAY = "local_numNativeDisplayLimit"

    const val NUM_DISPLAY = "local_numDisplayLimit"

    const val NUM_REQUEST = "local_numRequestLimit"

    const val NUM_CLICK = "local_numClickLimit"

    const val SAVE_DATE = "local_saveDate"

    /**
     * 保存的时间，用来判断是否是当天，不是当天要重置计数次数
     */
    private var saveDate
        get() = getSaveDateSetDefault()
        set(value) = AppPreferences.getInstance().put(SAVE_DATE, value)

    private fun getSaveDateSetDefault(): String {
        val date = AppPreferences.getInstance().getString(SAVE_DATE, "") ?: ""
        if (date == "") {
            saveDate = System.currentTimeMillis().toFormatTime4()
        }
        return date
    }


    /**
     * 广告请求是否到达限制
     */
    private inline val isRequestLimited: Boolean
        get() {
            val maxCount = AdConfigBean.adsConfigBean.numRequestLimit
            return maxCount > -1 && AppPreferences.getInstance()
                .getInt(NUM_REQUEST, 0) >= maxCount
        }

    /**
     * 广告展示是否到达限制
     */
    private inline val isDisplayLimited: Boolean
        get() {
            val maxCount = AdConfigBean.adsConfigBean.numDisplayLimit
            return maxCount > -1 && AppPreferences.getInstance()
                .getInt(NUM_DISPLAY, 0) >= maxCount
        }

    /**
     * 广告点击是否到达限制
     */
    private inline val isClickLimited: Boolean
        get() {
            val maxCount = AdConfigBean.adsConfigBean.numClickLimit
            return maxCount > -1 && AppPreferences.getInstance()
                .getInt(NUM_CLICK, 0) >= maxCount
        }

    private fun getAdEventMsg(adsType: AdsType): String {
        return when (adsType) {
            AdsType.OPEN -> "Open"
            AdsType.INSERT -> "Inter"
            AdsType.NATIVE -> "Native"
            else -> "Banner"
        }
    }

    /**
     * 是否显示广告
     *
     * @return true or false
     */
    fun isAdShow(adsType: AdsType, adEvent: AdEvent?): Boolean {

        if (BuildConfig.DEBUG) {
            return true
        }

        val currentDate = System.currentTimeMillis().toFormatTime4()
        if (saveDate != currentDate) {
            //如果已经不是今天了，就重置个数
            saveDate = currentDate
            AppPreferences.getInstance().put(NUM_DISPLAY, 0)
            AppPreferences.getInstance().put(NUM_REQUEST, 0)
            AppPreferences.getInstance().put(NUM_CLICK, 0)
        }
        if (isDisplayLimited) {

            val value = "current${getAdEventMsg(adsType)} " +
                    "show=${AppPreferences.getInstance().getInt(NUM_DISPLAY, 0)} " +
                    "${getAdEventMsg(adsType).lowercase()}_" + "max_show=${AdConfigBean.adsConfigBean.numDisplayLimit}"

            adEvent?.adLimited(value)
        }
        if (isClickLimited) {
            val value =
                "current${getAdEventMsg(adsType)}Click=${AppPreferences.getInstance().getInt(NUM_CLICK, 0)} "
            "${getAdEventMsg(adsType).lowercase()}_max_click=${AdConfigBean.adsConfigBean.numClickLimit}"

            adEvent?.adLimited(value)

        }
        if (isRequestLimited) {
            val value = "current${getAdEventMsg(adsType)}Request=${AppPreferences.getInstance().getInt(NUM_REQUEST, 0)} " +
                    "${getAdEventMsg(adsType).lowercase()}_max_request=${AdConfigBean.adsConfigBean.numRequestLimit}"

            adEvent?.adLimited(value)
        }

        return !(isDisplayLimited || isClickLimited || isRequestLimited)
    }

    private fun addNum(key: String) {
        val currentDate = System.currentTimeMillis().toFormatTime4()
        if (saveDate != currentDate) {
            //如果已经不是今天了，就重置个数
            saveDate = currentDate
            AppPreferences.getInstance().put(key, 1)
            return
        }
        AppPreferences.getInstance()
            .put(key, (AppPreferences.getInstance().getInt(key, 0) + 1))
    }

    fun addDisplayNum() {
        addNum(NUM_DISPLAY)
    }

    fun addRequestNum() {
        addNum(NUM_REQUEST)
    }

    fun addClickNum() {
        addNum(NUM_CLICK)
    }

    fun addNativeDisplayNum() {
        addNum(NUM_NATIVE_DISPLAY)
    }


    /**
     * 开屏限制
     */
    fun isIntervalOpenLimit(adEvent: AdEvent): Boolean {
        val passTime = ((System.currentTimeMillis() - openLastShowTime) / 1000).toInt()
        val interval = AdConfigBean.adsConfigBean.timeIntervalOpen
        val flag = passTime < interval
        LogEx.logDebug(adEvent.TAG, "open isIntervalOpenLimit=$flag passTime=$passTime interval=$interval")
        if (flag) {
            adEvent.adShowError("ad in timeInterval")
        }
        return flag
    }

    /**
     * 插屏限制
     */
    fun isIntervalInterLimit(adEvent: AdEvent): Boolean {
        val passTime = ((System.currentTimeMillis() - interLastShowTime) / 1000).toInt()
        val interval = AdConfigBean.adsConfigBean.timeInterval
        val flag = passTime < interval
        LogEx.logDebug(
            adEvent.TAG,
            "inter isIntervalInterLimit=$flag interLastShowTime=$interLastShowTime passTime=$passTime interval=$interval"
        )
        if (flag) {
            adEvent.adShowError("ad in timeInterval")
        }
        return flag
    }

    //开屏上次展示时间
    var openLastShowTime = 0L
        get() {
            return AppPreferences.getInstance().getLong("openLastShowTime", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("openLastShowTime", value, true)
        }

    //插屏上次展示时间
    var interLastShowTime = 0L
        get() {
            return AppPreferences.getInstance().getLong("interLastShowTime", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("interLastShowTime", value, true)
        }


    /**
     * 原生广告是否到达限制
     */
    private inline val isNativeLimited: Boolean
        get() {
            val maxCount = AdConfigBean.adsConfigBean.numNativeDisplayLimit
            return maxCount > -1 && AppPreferences.getInstance()
                .getInt(NUM_NATIVE_DISPLAY, 0) >= maxCount
        }

    fun isShowNative(adsType: AdsType, adEvent: AdEvent?): Boolean {
        val currentDate = System.currentTimeMillis().toFormatTime4()
        if (saveDate != currentDate) {
            //如果已经不是今天了，就重置个数
            saveDate = currentDate
            AppPreferences.getInstance().put(NUM_NATIVE_DISPLAY, 0)
        }
        val flag = isNativeLimited

        val todayNumber = AppPreferences.getInstance().getInt(NUM_NATIVE_DISPLAY, 0)
        val max = AdConfigBean.adsConfigBean.numNativeDisplayLimit

        LogEx.logDebug(adEvent?.TAG ?: "", "native todayNumber=$todayNumber max=$max  ")

        if (flag) {
            val value = "current${getAdEventMsg(adsType)} " +
                    "show=${todayNumber} " +
                    "${getAdEventMsg(adsType).lowercase()}_" + "max_show=${max}"
            adEvent?.adLimited(value)
        }
        return !flag
    }

}
