package melody.offline.music.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.force.update.drainage.UpdateUtil
import com.gyf.immersionbar.ktx.immersionBar
import com.lol.apex.ok.google.adlibrary.LoLAds
import com.lol.apex.ok.google.adlibrary.base.listener.LolLoadError
import com.lol.apex.ok.google.adlibrary.base.listener.LolShowError
import melody.offline.music.App
import melody.offline.music.ads.AdPlacement
import melody.offline.music.ads.AnalysisAdState
import melody.offline.music.ads.LolAdWrapper
import melody.offline.music.databinding.ActivityLaunchBinding
import melody.offline.music.util.AnalysisUtil
import melody.offline.music.util.LogTag

class LaunchActivity : MoBaseActivity() {
    companion object {
        private const val MSG_PROGRESS = 0
        private const val MSG_LOAD_AD_LOADED = 1
        private const val MSG_LOAD_AD_FAIL = 2

        const val FROM_TYPE = "STARTED_FROM_ON_ACTIVITY_STARTED_TYPE"
    }

    private lateinit var binding: ActivityLaunchBinding
    private val mMaxLoading = 10000L//最大超时
    private var progress = 0f
    private val delayMillis = mMaxLoading / 100
    private var type = -1

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            val progressBar = binding.customProgressBar
            if (!isFinishing && !isDestroyed) {
                when (msg.what) {
                    MSG_PROGRESS -> {
                        if (progress >= 100f) {//超时
                            //超时就是没有广告，就是广告show失败了
                            val map =
                                mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "No cache for ads"))
                            AnalysisUtil.placeToLogEvent(
                                AdPlacement.INST_SPLASH, AnalysisAdState.AD_SHOW_FAILED, map
                            )
                            toMainActivity()
                            return
                        }
                        if (adCanShow()) {
                            sendEmptyMessageDelayed(MSG_LOAD_AD_LOADED, delayMillis)
                            removeMessages(MSG_PROGRESS)
                            return
                        }
                        progress += 1
                        progressBar.setProgress(progress)
                        sendEmptyMessageDelayed(MSG_PROGRESS, delayMillis)
                    }

                    MSG_LOAD_AD_LOADED -> {
                        if (progress >= 100f) {
                            showAd()
                            removeMessages(MSG_LOAD_AD_LOADED)
                            return
                        }
                        progress += 1
                        progressBar.setProgress(progress)
                        sendEmptyMessageDelayed(MSG_LOAD_AD_LOADED, delayMillis)
                    }

                    MSG_LOAD_AD_FAIL -> {
                        sendEmptyMessageDelayed(MSG_LOAD_AD_LOADED, delayMillis)
                        removeMessages(MSG_LOAD_AD_FAIL)
                        removeMessages(MSG_PROGRESS)
                    }
                }
            }
        }
    }

    override suspend fun main() {
        binding = ActivityLaunchBinding.inflate(layoutInflater)
        setContentView(binding.root)
        UpdateUtil.instance.init(App.app)
        AnalysisUtil.logEvent(AnalysisUtil.LAUNCH_PV)
        type = intent.getIntExtra(FROM_TYPE, -1)
        loadAd()
        handler.sendEmptyMessageDelayed(MSG_PROGRESS, delayMillis)
        immersionBar {
            fullScreen(true)
            statusBarDarkFont(false)
        }
    }

    private fun toMainActivity() {
        if (!withPermission()) {
            if (type == 1) {//如果type等于1，则是从后台进入的应用，不进行跳转直接关闭启动页
                finish()
            } else {
                startActivity(Intent(this, MainActivity::class.java))
                finish()
            }
        } else {
            if (type == 1) {
                finish()
            } else {
                startActivity(Intent(this, PrimaryActivity::class.java))
                finish()
            }
        }
    }

    private fun loadAd() {
        LolAdWrapper.shared.loadAd(
            this,
            AdPlacement.INST_SPLASH,
            object : LolAdWrapper.LoLLoadListener {
                override fun loadFailed(error: LolLoadError?) {
                    handler.sendEmptyMessage(MSG_LOAD_AD_FAIL)
                }
            })

        LolAdWrapper.shared.loadAdIfNotCached(this, AdPlacement.INST_BACKUP_ADS)
        LolAdWrapper.shared.loadAdIfNotCached(this, AdPlacement.INST_INTO_PLAY)
    }

    private fun adCanShow(): Boolean {
        return LolAdWrapper.shared.hasCache(AdPlacement.INST_SPLASH)
    }

    private fun showAd() {
        LolAdWrapper.shared.showAdIfCached(
            this,
            AdPlacement.INST_SPLASH,
            object : LolAdWrapper.LolShowListener {
                override fun closed() {
                    toMainActivity()
                }

                override fun showFailed(error: LolShowError?) {
                    toMainActivity()
                }
            })
    }

    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {

    }
}