package com.tgv.malware.business.ads

import android.app.Activity
import android.app.Dialog
import com.tgv.malware.business.ads.LimitUtils.openInterLastShowTime
import java.lang.ref.WeakReference


class AdState<T>() {

    var adDialog: Dialog? = null


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

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

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


    /**
     * 用于保存引用现有页面，在此页面显示广告(因为要等待广告加载完毕)
     */
    var activityRef: WeakReference<Activity>? = null

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

    /**
     * 上次展示时间
     */
//    var lastShowTime: Long = 0


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

        adDialog?.dismiss()
        adDialog = null

        openInterLastShowTime = System.currentTimeMillis()
    }

    fun onAdHidden() {

        //重置下上次展示的时间,避免看广告的时间算入间隔
        openInterLastShowTime = System.currentTimeMillis()

    }

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

        currentAd = null
        currentAdEvent = null
        activityRef = null
    }

    fun onAdLoaded(ad: T?, adEvent: AdEvent?) {
        //这里可能提前设置,所有可以不设置,max回调的类型可能不同
        if (ad != null) {
            currentAd = ad
        }
        if (adEvent != null) {
            currentAdEvent = adEvent
        }
        loadingAd = false
        lastLoadTime = System.currentTimeMillis()
    }

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

    }

    fun adAvailable() =
        currentAd != null || ((System.currentTimeMillis() - lastLoadTime) / 1000 / 60).toInt() < 30

}
