package com.base.locationsharewhite.ads.admob

import com.base.locationsharewhite.ads.AdsMgr
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.KotlinExt.toFormatTime4

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

    const val NUM_REQUEST = "numRequestLimit"

    const val NUM_CLICK = "numClickLimit"

    const val SAVE_DATE = "SAVE_DATE"

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


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

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

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

    /**
     * 是否显示广告
     *
     * @return true or false
     */
    fun isAdShow(): Boolean {
        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)
        }
        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)
    }


}