package com.keyboard.journey.ad

import android.app.Activity
import java.util.Random

object MaxAdsInsUtil {

    object Placement {
        const val SPLASH_AD_ID = "f17d90b8ffcd8c43"
        const val MAX_AD_ID_ONE = "b940838b4e632b48"
        const val MAX_AD_ID_TOW = "872bcabcd258447b"

        val adPlaceAllList = listOf(
            SPLASH_AD_ID,
            MAX_AD_ID_ONE,
            MAX_AD_ID_TOW
        )
    }

    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: AdLoadListener? = null) {
        if (act.isFinishing || canShowAd(placement)) return
        loadMaxAd(act, placement, listener)
    }

    fun showAdRandomMode(act: Activity) {
        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]
            showAdIfCached(act, place)
        }
    }

    fun showAdIfCached(act: Activity, placement: String, listener: AdShowListener? = null) {
        if (act.isFinishing || !canShowAd(placement)) {
            listener?.onAdShowFailed(AdShowFailed("No cache for ads"))
        } else {
            showMaxAd(act, placement, listener)
        }
    }

    fun loadMaxAd(
        act: Activity,
        adID: String,
        loadListener: AdLoadListener?
    ): MaxAdInstLoad {
        return MaxAdInstLoad(act, adID, loadListener)
    }

    fun showMaxAd(
        act: Activity,
        adID: String,
        listener: AdShowListener?
    ): MaxAdInstShower {
        return MaxAdInstShower(act, adID, listener)
    }

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