package com.flowing.light.board.ironad

import android.app.Activity
import android.app.Application
import android.os.CountDownTimer
import android.os.Handler
import android.util.Log

import com.unity3d.mediation.LevelPlay
import com.unity3d.mediation.LevelPlayAdError
import com.unity3d.mediation.LevelPlayAdInfo
import com.unity3d.mediation.LevelPlayConfiguration
import com.unity3d.mediation.LevelPlayInitError
import com.unity3d.mediation.LevelPlayInitListener
import com.unity3d.mediation.LevelPlayInitRequest
import com.unity3d.mediation.interstitial.LevelPlayInterstitialAd
import com.unity3d.mediation.interstitial.LevelPlayInterstitialAdListener
import com.unity3d.services.UnityAdsSDK


object AdManager {

    //上次广告展示时刻
    var LAST_AD_SHOW = 0L

    const val type_no_cache = 0
    const val type_has_cache = 1
    const val type_show_success = 2
    const val type_show_close = 3
    const val type_show_fail = 4


    var place1Id = ""
    var place2Id = ""
    var place3Id = ""


    var place1LoadFail = false
    var place2LoadFail = false
    var place3LoadFail = false

    val list = mutableListOf<LevelPlayInterstitialAd>()
    var mContext: Application? = null
    var mTAG = "-----------IronSource-----------"


    fun init(
        tag: String,
        context: Application,
        appKey: String,
        id1: String,
        id2: String,
        id3: String,
        showDebugUI: Boolean,
        onInitSuccess: (p0: LevelPlayConfiguration) -> Unit,
        onInitFail: (p0: LevelPlayInitError) -> Unit
    ) {
        mTAG = tag
        mContext = context
        place1Id = id1
        place2Id = id2
        place3Id = id3

        if(showDebugUI){
            LevelPlay.setMetaData("is_test_suite", "enable")
        }
        val initRequest = LevelPlayInitRequest.Builder(appKey)
            .build()
        LevelPlay.init(context, initRequest, object : LevelPlayInitListener {
            override fun onInitSuccess(p0: LevelPlayConfiguration) {
                onInitSuccess(p0)
                //测试工具
                if (showDebugUI) {
                    mContext?.let {
                        LevelPlay.launchTestSuite(it)
                    }
                } else {
                    loadAllAd()
                }
            }

            override fun onInitFailed(p0: LevelPlayInitError) {
                onInitFail(p0)
            }

        })



    }


    @JvmStatic
    fun loadAllAd() {
        if (list.size <= 0) {
            place1LoadFail = false
            place2LoadFail = false
            place3LoadFail = false
            val iSAd1 = LevelPlayInterstitialAd(place1Id)
            val iSAd2 = LevelPlayInterstitialAd(place2Id)
            val iSAd3 = LevelPlayInterstitialAd(place3Id)
            list.add(iSAd1)
            list.add(iSAd2)
            list.add(iSAd3)
        }
        for (ad in list) {
            if (!ad.isAdReady) {
                setCallBack(ad, object : IronListener {
                    override fun onLoaded() {
                    }

                    override fun onLoadFail() {
                        Log.d(mTAG, "-loadFail------placeId------${ad.adId}")
                        if (ad.adId == place1Id) {
                            place1LoadFail = true
                        }
                        if (ad.adId == place2Id) {
                            place2LoadFail = true
                        }
                        if (ad.adId == place3Id) {
                            place3LoadFail = true
                        }
                    }

                    override fun onClose() {

                    }

                    override fun onShowFail() {

                    }

                    override fun onShowSuccess() {

                    }
                })
                ad.loadAd()
            }
        }
    }

    @JvmStatic
    fun getReadyAd(): LevelPlayInterstitialAd? {
        list.shuffle()
        for (ad in list) {
            if (ad.isAdReady) {
                Log.d(mTAG, "-cache------------")
                return ad
            }
        }
//        Log.d(mTAG, "-no cache------------")
        return null
    }


    @JvmStatic
    fun showWelcomeAd(
        activity: Activity,
        totalTim: Long,
        countAction: (millisUntilFinished: Long) -> Unit,
        goMain: () -> Unit
    ): CountDownTimer {
        var alreadyShow = false
        var timer: CountDownTimer? = null
        timer = object : CountDownTimer(totalTim, 100) {
            override fun onTick(millisUntilFinished: Long) {
                countAction(millisUntilFinished)
                Log.d(mTAG, "onTick ${Thread.currentThread().name}  timer=${timer}")
                if (!alreadyShow) {
                    showAD(activity) {
                        if (it == type_has_cache) {
                            alreadyShow = true
                        }
                        if (it == type_show_close || it == type_show_fail) {
                            Log.d(
                                mTAG,
                                "goMain 111 ${Thread.currentThread().name}   "
                            )
                            goMain()
                        }

                    }
                }
            }

            override fun onFinish() {
                Log.d(mTAG, "onFinish()  ${Thread.currentThread().name}   ")
                if (!alreadyShow) {
                    showAD(activity) {
                        if (it == type_show_close || it == type_show_fail || it == type_no_cache) {
                            Log.d(
                                mTAG,
                                "goMain 222 ${Thread.currentThread().name}   "
                            )
                            goMain()
                        }
                    }
                }
            }
        }
        return timer
    }

    @JvmStatic
    fun showWelComeAd(
        activity: Activity,
        handler: Handler,
        totalTime: Long,
        listener: WelcomeListener
    ): Runnable {
        var remainingTime = totalTime
        var interval = 100L
        var alreadyShow = false

        //继续更新进度
        var isContinue = true
        return object : Runnable {
            override fun run() {
                remainingTime -= interval
                if (remainingTime <= 0) {
                    if (!alreadyShow) {
                        showAD(activity) {
                            if (it == type_show_close || it == type_show_fail || it == type_no_cache) {
                                Log.d(
                                    mTAG,
                                    "goMain 222 ${Thread.currentThread().name}   "
                                )
                                listener.goMain()
                            }
                        }
                    }
                } else {
                    val progress = (100 - remainingTime * 100 / totalTime).toInt()
                    listener.onTime(progress)
                    if (!alreadyShow) {
                        if (place1LoadFail
                            && place2LoadFail
                            && place3LoadFail
                        ) {
                            isContinue = false
                            listener.goMain()
                            Log.d(
                                mTAG,
                                "goMain 000 三个id都加载失败 ${Thread.currentThread().name}   "
                            )

                        }
                        showAD(activity) {
                            if (it == type_has_cache) {
                                alreadyShow = true
                            }
                            if (it == type_show_close || it == type_show_fail) {
                                Log.d(
                                    mTAG,
                                    "goMain 111 ${Thread.currentThread().name}   "
                                )
                                isContinue = false
                                listener.goMain()
                            }

                        }
                    }
                    if (isContinue)
                        handler.postDelayed(this, interval)
                }
            }
        }
    }


    private fun setCallBack(ad: LevelPlayInterstitialAd, listener: IronListener) {
        ad.setListener(object : LevelPlayInterstitialAdListener {
            override fun onAdLoaded(p0: LevelPlayAdInfo) {
                listener.onLoaded()
            }

            override fun onAdLoadFailed(p0: LevelPlayAdError) {
                listener.onLoadFail()
            }

            override fun onAdDisplayed(p0: LevelPlayAdInfo) {
                listener.onShowSuccess()
            }

            override fun onAdClosed(p0: LevelPlayAdInfo) {
                super.onAdClosed(p0)
                listener.onClose()
            }

            override fun onAdClicked(p0: LevelPlayAdInfo) {
                super.onAdClicked(p0)
            }

            override fun onAdDisplayFailed(p0: LevelPlayAdError, p1: LevelPlayAdInfo) {
                super.onAdDisplayFailed(p0, p1)
                listener.onShowFail()
            }


        })
    }


    @JvmStatic
    private fun showAD(activity: Activity, action: (type: Int) -> Unit) {
        val readyAd = getReadyAd()
        if (readyAd != null) {
            Log.d(mTAG, "readyAd  ${readyAd.adId}   ")
            action(type_has_cache)
            setCallBack(readyAd, object : IronListener {
                override fun onLoaded() {
                }

                override fun onLoadFail() {

                }

                override fun onClose() {
                    action(type_show_close)
                }

                override fun onShowFail() {
                    action(type_show_fail)
                }

                override fun onShowSuccess() {
                    action(type_show_success)
                    LAST_AD_SHOW = System.currentTimeMillis()
                }
            })
            readyAd.showAd(activity)
        } else {
            action(type_no_cache)

        }
    }

    @JvmStatic
    fun showIsAd(activity: Activity, listener: onActionListener) {
        showAD(activity) { type ->
            if (type == type_no_cache || type == type_show_close || type == type_show_fail) {
                listener.onAction()
            }
        }
    }
}