package com.trace.drawing.people.max

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.CountDownTimer
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager

import com.applovin.mediation.ads.MaxInterstitialAd
import com.trace.drawing.people.tools.App


object WelComManager {

    private lateinit var timer: CountDownTimer

    private var need_Show = true

    private lateinit var lists: List<MaxInterstitialAd>
    private val mTag = App.TAG

    @JvmStatic
    fun initTimer(activity: Activity, countTime: Long,countAction: (Long) -> Unit, goMainAction: () -> Unit): CountDownTimer {
        need_Show = true
        timer = object : CountDownTimer(countTime, 100) {
            override fun onTick(millisUntilFinished: Long) {
                countAction.invoke(millisUntilFinished)
                if (need_Show) {
                    MaxManager.ShowAd(activity) {
                        Log.d(mTag, "--onTick----------it=$it")
                        if (it == MaxManager.type_has_cache) {
                            need_Show = false
                        }
                        if (it == MaxManager.type_show_close || it == MaxManager.type_show_fail) {
                            Log.d(mTag, "--onTick---------enter")
                            goMainAction.invoke()
                        }
                    }
                }
            }

            override fun onFinish() {
                if (need_Show) {
                    MaxManager.ShowAd(activity) {
                        if (it == MaxManager.type_show_close || it == MaxManager.type_show_fail || it == MaxManager.type_no_cache) {
                            Log.d(mTag, "--onFinish---------enter")
                            goMainAction.invoke()
                        }
                    }
                }
            }
        }
        startAd(activity)
        return timer
    }

    private fun startAd(activity: Activity) {
        if (!App.initSDkOK) {
            LocalBroadcastManager.getInstance(activity)
                .registerReceiver(object : BroadcastReceiver() {
                    override fun onReceive(context: Context?, intent: Intent?) {
                        lists = MaxManager.onLoadAd()
                        timer.start()
                        Log.d(mTag, "------------1sucess")
                    }
                }, IntentFilter(App.initAction))
        } else {
            lists = MaxManager.onLoadAd()
            timer.start()
            Log.d(mTag, "------------2sucess")
        }
    }


}