package com.base.locationsharewhite.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.lifecycle.lifecycleScope
import com.base.locationsharewhite.R
import com.base.locationsharewhite.ads.AdsMgr
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.bean.ConstObject.appLanguageCountrySp
import com.base.locationsharewhite.bean.ConstObject.appLanguageSp
import com.base.locationsharewhite.bean.ConstObject.ifAgreePrivacy
import com.base.locationsharewhite.bean.ConstObject.isFirstLauncher
import com.base.locationsharewhite.databinding.ActivitySplashBinding
import com.base.locationsharewhite.fcm.NotificationHoverUtils
import com.base.locationsharewhite.fcm.PopupConstObject
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.ui.howuse.HowUseActivity
import com.base.locationsharewhite.ui.main.LocationCodeActivity
import com.base.locationsharewhite.ui.main.LocationShareActivity
import com.base.locationsharewhite.ui.main.MainActivity
import com.base.locationsharewhite.ui.set.LanguageActivity
import com.base.locationsharewhite.ui.set.SettingActivity
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.LogEx
import com.base.locationsharewhite.utils.SolarEngineUtils.initSolarEngine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity<ActivitySplashBinding>(), SplashView {

    private lateinit var splashPresenter: SplashPresenter
    private var progressJob: Job? = null

    override val binding: ActivitySplashBinding by lazy {
        ActivitySplashBinding.inflate(layoutInflater)
    }

    private var actionId: String? = null

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        //        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        splashPresenter = SplashPresenter(this)
        actionId = intent.extras?.getString("actionId")
        LogEx.logDebug(TAG, "actionId=$actionId")
        if (actionId != null) {
            NotificationHoverUtils.stopNotificationHandler()
        }

        if (ifAgreePrivacy) {
            agreePrivacy()
        }
        initSolarEngine(true)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            launcher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS)) {
                LogEx.logDebug(TAG, "POST_NOTIFICATIONS")
            }
        }
    }

    override fun showAd() {

    }

    override fun agreePrivacy() {
        AdsMgr.showOpen(this, true, object : AdsShowCallBack() {
            override fun show() {
                LogEx.logDebug(TAG, "AdsShowCallBack show")
                splashPresenter.cancelJumpJob()
                cancelProgressJob()
            }

            override fun close(where: Int) {
                LogEx.logDebug(TAG, "AdsShowCallBack close")
                jumpNext()
            }

            override fun failed(where: Int) {
                LogEx.logDebug(TAG, "AdsShowCallBack failed")
                jumpNext()
            }

            override fun googleFailed(where: Int) {
                LogEx.logDebug(TAG, "AdsShowCallBack googleFailed")
                jumpNext()
            }

        })

        splashPresenter.startJumpJob = true
        splashPresenter.startJumpJob(lifecycleScope)

        startProgressJob = true
        startProgressJob()
    }

    private var jump: AtomicBoolean = AtomicBoolean(false)
    override fun jumpNext() {
        if (jump.get()) {
            return
        }
        jump.set(true)

        binding.progressbar.progress = 100

        binding.root.postDelayed({
            if (isFirstLauncher) {
                isFirstLauncher = false
                firstLauncherJump()
            } else {
                handleActionIdJump()
            }
        }, 100)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handleActionIdJump()
    }

    private fun handleActionIdJump() {
        actionId = intent.extras?.getString("actionId")
        LogEx.logDebug(TAG, "handleActionIdJump actionId=$actionId")

        when (actionId) {
            PopupConstObject.ACTION_STAY_HOME -> {
                startActivity(Intent(this, MainActivity::class.java).apply {
                    putExtra("actionId", actionId)
                    putExtra("where", "ACTION_STAY_HOME")
                })
            }

            PopupConstObject.ACTION_STAY_MY_CODE -> {
                startActivity(Intent(this, LocationCodeActivity::class.java).apply {
//                    putExtra("actionId", actionId)
                })
            }

            PopupConstObject.ACTION_STAY_SHARE -> {
                startActivity(Intent(this, LocationShareActivity::class.java).apply {
//                    putExtra("actionId", actionId)
                })
            }

            PopupConstObject.ACTION_STAY_SETTING -> {
                startActivity(Intent(this, SettingActivity::class.java).apply {
//                    putExtra("actionId", actionId)
                })
            }

            else -> {
                startActivity(Intent(this, MainActivity::class.java).apply {
                    putExtra("actionId", actionId)
                    putExtra("where", "actionId else")
                })
            }

        }

        finish()
        intent.extras?.clear()
    }

    private fun firstLauncherJump() {
        if (appLanguageSp + "_" + appLanguageCountrySp != Locale.ENGLISH.language + "_" + Locale.ENGLISH.country) {
            startActivity(Intent(this, LanguageActivity::class.java).apply {
                putExtra("isGuide", true)
            })
        } else {
            startActivity(Intent(this, HowUseActivity::class.java).apply {
                putExtra("isGuide", true)
            })
        }
        finish()
    }

    override fun onPause() {
        super.onPause()
        splashPresenter.cancelJumpJob()
        cancelProgressJob()
    }

    override fun onResume() {
        super.onResume()
        splashPresenter.startJumpJob(lifecycleScope)
        startProgressJob()
    }

    private var startProgressJob: Boolean = false

    private fun startProgressJob() {
        if (ifAgreePrivacy && startProgressJob) {
            if (progressJob == null) {
                progressJob = lifecycleScope.launch(Dispatchers.Main) {
                    while (isActive) {
                        binding.progressbar.progress += 1
                        binding.tvTip.text = resources.getString(R.string.moment_please_s, binding.progressbar.progress)
                        delay(200)
                    }
                }
            }
        }
    }

    private fun cancelProgressJob() {
        progressJob?.cancel()
        progressJob = null
    }

}