package com.base.appzxhy.business.ads

import com.base.appzxhy.BuildConfig
import com.base.appzxhy.bean.config.AdConfigBean
import com.base.appzxhy.utils.AppPreferences
import com.base.appzxhy.utils.KotlinExt.toFormatTime4


/**
 * 控制广告计数与判断显示条件
 *
 */
object LimitUtils {
    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 isIntervalLimited(adEvent: AdEvent?): Boolean {
        val flag = ((System.currentTimeMillis() - openInterLastShowTime) / 1000).toInt() < (AdConfigBean.adsConfigBean.timeInterval)
        if (flag) {
            adEvent?.adLimited("ad in timeInterval")
        }
        return flag
    }

    //开屏和插页上一次展示时间共用,避免开屏插页连弹
    var openInterLastShowTime = 0L
        get() {
            return AppPreferences.getInstance().getLong("openInterLastShowTime", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("openInterLastShowTime", value, true)
        }
}