package com.colorful.keyboard.theme.ad

import android.app.Activity
import com.colorful.keyboard.theme.App
import com.colorful.keyboard.theme.myutil.AppSharedPreferences
import com.unity3d.services.ads.api.Show
import java.util.Random

object AdsInsUtil {

    object Placement {
        const val TOP_ON_AD_ONE = "n66b1cf2f2c70c"
        const val TOP_ON_AD_TOW = "n66b1cf2f04a38"
        const val TOP_ON_AD_THREE = "n66b1cf2ecd817"

        val adPlaceAllList = listOf(
            TOP_ON_AD_ONE,
            TOP_ON_AD_TOW,
            TOP_ON_AD_THREE
        )
    }

    fun loadSplashAllAd(act: Activity) {
        Placement.adPlaceAllList.drop(1).forEach { placement ->
            loadAdIfNotCached(act, placement)
        }
    }

    fun loadAllAdIsNotCached(act: Activity) {
        Placement.adPlaceAllList.forEach { placement ->
            loadAdIfNotCached(act, placement)
        }
    }

    fun loadAdIfNotCached(act: Activity, placement: String, listener: LoadListener? = null) {
        if (act.isFinishing || canShowAd(placement)) return
        loadAd(act, placement, listener)
    }

    fun showAdRandomModeAndTiming(act: Activity, listener: ShowListener? = null) {
        val adPlace: MutableList<String> = ArrayList()
        Placement.adPlaceAllList.forEach { placement ->
            if (canShowAd(placement)) {
                adPlace.add(placement)
            }
        }
        if (adPlace.isNotEmpty()) {
            val placeId = Random().nextInt(adPlace.size)
            val place = adPlace[placeId]
            showAd(act, place, listener)
        }
    }

    fun canShowAd(adID: String): Boolean {
        InstAdCacheManager.instance.getAdCache(adID)?.let {
            return it.isAdReady
        } ?: let {
            return false
        }
    }

    fun loadAd(
        act: Activity,
        adID: String,
        loadListener: LoadListener?
    ): AdInstLoad {
        return AdInstLoad(act, adID, loadListener)
    }

    fun showAd(
        act: Activity,
        adID: String,
        listener: ShowListener?
    ): AdInstShower {
        return AdInstShower(act, adID, listener)
    }

    fun showAdTiming(act: Activity, placement: String, listener: ShowListener? = null) {
        //当前时间减去旧时间,才展示广告（满足间隔时间才show广告）
        val showAdIntervalTime = AppSharedPreferences(App.app).getShowAdIntervalTime()
        if (System.currentTimeMillis() - App.app.lastAdDisplayTime.get() >= showAdIntervalTime) {
            //判断当前广告位是否可以show，不能show则判断补位广告是否可以show。
            if (act.isFinishing || !canShowAd(placement)) {
                showAd(act, placement, listener)
            } else {
                showAd(act, placement, listener)
            }
        }
    }
}