package com.duben.microtribe.ui.activitys

import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import com.duben.microtribe.R
import com.duben.microtribe.ad.AdStatusListener
import com.duben.microtribe.ad.splash.SplashManager
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.microtribe.ui.widgets.countdowntimer.CountDownTimerSupport
import com.duben.microtribe.ui.widgets.countdowntimer.OnCountDownTimerListener
import kotlinx.android.synthetic.main.activity_gromore.*

/**
 * 描述：gromore后台返回广告
 * 作者：孟崔广
 * 时间：2023/8/04 13:52
 */
class SplashForeAdActivity : BaseActivity() {

    //是否强制跳转到主页面
    private var onPaused = false

    var mTimer: CountDownTimerSupport? = null

    private val mMainHandler = Handler(Looper.getMainLooper())

    override fun getContentViewLayoutID() = R.layout.activity_gromore_fore

    override fun isApplyKitKatTranslucency() = false

    override fun initViewsAndEvents() {
        var timeout = 200L

        mMainHandler.postDelayed({
            SplashManager.showAd(
                this@SplashForeAdActivity,
                fl_gromore_root,
                object : AdStatusListener {
                    override fun adSuccess() {

                    }

                    override fun adFail() {
                        goToMainActivity()
                    }

                    override fun adClose(vo: HashMap<String, Any>?) {
                        goToMainActivity()
                    }
                })

            // 防止广告展示异常，界面卡住
            startTime()
        }, timeout)
    }

    override fun onResume() {
        super.onResume()

        //判断是否该跳转到主页面
        if (onPaused) {
            goToMainActivity()
        }
    }

    override fun onPause() {
        super.onPause()
        onPaused = true
    }

    override fun onDestroy() {
        super.onDestroy()
        onDestroyTimer()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    /**
     * 跳转到主页面
     */
    private fun goToMainActivity() {
        finish()
    }

    /**
     * 防止广告展示异常，界面卡住
     */
    private fun startTime() {
        onDestroyTimer()
        mTimer = CountDownTimerSupport(3000L, 1000L)
        mTimer?.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                if (!isFinishing) {
                    // 3秒广告都没有展示 则进入首页
                    if (!SplashManager.getAdStatus()) {
                        onDestroyTimer()
                        goToMainActivity()
                    }
                }
            }
        })
        mTimer?.start()
    }

    private fun onDestroyTimer() {
        mTimer?.stop()
        mTimer = null
    }
}
