package com.assimilate.alltrans.viewui

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.assimilate.alltrans.MyApp
import com.assimilate.alltrans.common.FirebaseAnalyticsHelper
import com.assimilate.alltrans.common.LolAdWrapper
import com.assimilate.alltrans.databinding.ActivityWelBinding
import com.lol.apex.ok.google.adlibrary.base.listener.LolLoadError
import com.lol.apex.ok.google.adlibrary.base.listener.LolShowError

class WelActivity : AppCompatActivity() {
    companion object {
        private const val MSG_PROGRESS = 0
        private const val MSG_LOAD_AD_LOADED = 1
        private const val MSG_LOAD_AD_FAIL = 2
    }

    private lateinit var binding: ActivityWelBinding

    private val mMaxLoading = 10 * 1000L//最大超时
    private var progress = 0f
    private val delayMillis = mMaxLoading / 100
    private var place: String = MyApp.Config.start_cold_int_auto


    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失败了
                            toNextPage()
                            return
                        }
                        if (adCanShow()) {
                            //能展示走展示，移除进度，结束循环
                            sendEmptyMessageDelayed(MSG_LOAD_AD_LOADED, delayMillis)
                            removeMessages(MSG_PROGRESS)
                            return
                        }

                        // 继续加载进度，除非上面条件有成立
                        progress += 1
                        progressBar.progress = progress.toInt()
                        sendEmptyMessageDelayed(MSG_PROGRESS, delayMillis)
                    }

                    MSG_LOAD_AD_LOADED -> {

                        //展示广告，移除加载，移除进度条，结束循环
                        //    if (progress >= 100f) {
                        showAd()
                        removeMessages(MSG_LOAD_AD_LOADED)
                        removeMessages(MSG_PROGRESS)
                        return
                        //   }

//                        progress += 1
//                        progressBar.progress = progress.toInt()
//                        sendEmptyMessageDelayed(MSG_LOAD_AD_LOADED, delayMillis)
                    }

                    MSG_LOAD_AD_FAIL -> {
                        if (progress < 77f) {
                            progress = 77f
                        }
                        // 失败走进度条,移除失败
                        sendEmptyMessageDelayed(MSG_PROGRESS, delayMillis)
                        removeMessages(MSG_LOAD_AD_FAIL)
                        // removeMessages(MSG_PROGRESS)
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        binding = ActivityWelBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initSet()
    }

    private fun initSet() {
        backPressedCall()

        // 判断走冷启动还是热启动广告
        place = if (!MyApp.app.isFirstLaunch) {
            MyApp.Config.start_cold_int_auto
        } else {
            MyApp.Config.start_hot_int_auto

        }
        //请求广告，启动进度条
        loadAd()
        handler.sendEmptyMessageDelayed(MSG_PROGRESS, delayMillis)
    }

    private fun backPressedCall() {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
            }
        }
        onBackPressedDispatcher.addCallback(this, callback)
    }

    override fun onResume() {
        super.onResume()
        FirebaseAnalyticsHelper.launchPvEvent()
    }

    private fun toNextPage() {
        // 热启动关闭加载页，冷启动进入主页
        if (MyApp.app.isFirstLaunch) {
            startActivity(Intent(this@WelActivity, MainActivity::class.java))
        } else {
            finish()
        }
    }

    private fun loadAd() {
        LolAdWrapper.shared.loadAd(
            this,
            place,
            object : LolAdWrapper.LoLLoadListener {
                override fun loadFailed(error: LolLoadError?) {
                    handler.sendEmptyMessage(MSG_LOAD_AD_FAIL)
                }
            })
        LolAdWrapper.shared.loadAdIfNotCached(this, MyApp.Config.backup_int_auto)


    }

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

    private fun showAd() {
        LolAdWrapper.shared.showAdIfCached(
            this,
            place,
            object : LolAdWrapper.LolShowListener {
                override fun closed() {
                    toNextPage()
                }

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