package com.dumpster.cleaner.business.ads

import android.app.Dialog
import com.dumpster.cleaner.business.ads.AdsType.Companion.INSERT
import com.dumpster.cleaner.business.ads.AdsType.Companion.OPEN
import com.dumpster.cleaner.business.ads.LimitUtils.interLastShowTime
import com.dumpster.cleaner.business.ads.LimitUtils.openLastShowTime


class AdState<T>() {


    var adDialog: Dialog? = null


    /**
     * 当前缓存的广告
     */
    var currentAd: T? = null

    /**
     * 当前缓存广告对应的event
     */
    var currentAdEvent: AdEvent? = null

    /**
     * 是否正在缓存加载广告
     */
    var loadingAd: Boolean = false

    /**
     * 上一次的缓存成功时间
     */
    var lastLoadTime: Long = 0


    /**
     * 广告已经展示
     */
    fun onAdDisplayed(adsType: AdsType) {
        currentAd = null
        currentAdEvent = null

        adDialog?.dismiss()
        adDialog = null

        if (adsType == OPEN) {
            openLastShowTime = System.currentTimeMillis()
        }

        if (adsType == INSERT) {
            interLastShowTime = System.currentTimeMillis()
        }
    }

    fun onAdHidden(adsType: AdsType) {

        //重置下上次展示的时间,避免看广告的时间算入间隔
        if (adsType == OPEN) {
            openLastShowTime = System.currentTimeMillis()
        }

        if (adsType == INSERT) {
            interLastShowTime = System.currentTimeMillis()
        }

    }

    fun onAdDisplayFailed() {
        adDialog?.dismiss()
        adDialog = null

        currentAd = null
        currentAdEvent = null
    }

    fun loadStart(adEvent: AdEvent) {
        loadingAd = true
        currentAdEvent = adEvent
    }

    fun onAdLoaded(ad: T?) {
        currentAd = ad

        loadingAd = false
        lastLoadTime = System.currentTimeMillis()
    }

    fun onAdLoadFailed() {
        adDialog?.dismiss()
        adDialog = null
        loadingAd = false

    }

    fun needLoad() = currentAd == null || ((System.currentTimeMillis() - lastLoadTime) / 1000 / 60).toInt() > 30


}
