package com.offline.music.player.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.offline.music.player.MusicApplication


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,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(MaxManager.AD_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(MaxManager.AD_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(MaxManager.AD_TAG, "--onFinish---------enter")
                            goMainAction.invoke()
                        }
                    }
                }
            }
        }
        startAd(activity)
        return timer
    }

    private fun startAd(activity: Activity) {
        if (!MusicApplication.initSDkOK) {
            timer.start()
            LocalBroadcastManager.getInstance(activity)
                .registerReceiver(object : BroadcastReceiver() {
                    override fun onReceive(context: Context?, intent: Intent?) {
                        lists = MaxManager.onLoadAd()

                        Log.d(MaxManager.AD_TAG, "------------1sucess")
                    }
                }, IntentFilter(MusicApplication.initAction))
        } else {
            lists = MaxManager.onLoadAd()
            timer.start()
            Log.d(MaxManager.AD_TAG, "------------2sucess")
        }
    }


}