package com.lc.myapplication.security.locks.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.lc.myapplication.security.locks.Securitylocks


object WelComManager {

    private lateinit var timer: CountDownTimer

    private var need_Show = true

    private lateinit var lists: List<MaxInterstitialAd>

    @JvmStatic
    fun initTimer(
        activity: Activity,
        countTime: Long,
        timAction: (time: Long) -> Unit,
        goMainAction: () -> Unit
    ): CountDownTimer {
        need_Show = true
        timer = object : CountDownTimer(countTime, 100) {
            override fun onTick(millisUntilFinished: Long) {
                timAction.invoke(millisUntilFinished)
                if (need_Show) {
                    MaxManager.ShowAd(activity) {
                        Log.d(Securitylocks.TAG, "--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(Securitylocks.TAG, "--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(Securitylocks.TAG, "--onFinish---------enter")
                            goMainAction.invoke()
                        }
                    }
                }
            }
        }
        startAd(activity)
        return timer
    }

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


}