package com.base.datarecovery.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.text.SpannableString
import android.text.Spanned
import android.text.style.UnderlineSpan
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.MyApplication
import com.base.datarecovery.activity.guide.GuideActivity
import com.base.datarecovery.activity.junkclean.ScanJunkActivity
import com.base.datarecovery.activity.privacyspace.PrivacyPinOneActivity
import com.base.datarecovery.activity.privacyspace.PrivacySpaceActivity
import com.base.datarecovery.activity.recovery.FileScanResultActivity
import com.base.datarecovery.activity.repeat.RepeatActivity
import com.base.datarecovery.activity.screenshot.ScreenShotActivity
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.ads.admob.AdmobInterstitialUtils
import com.base.datarecovery.ads.admob.AdmobNativeUtils
import com.base.datarecovery.ads.admob.AdmobOpenUtils
import com.base.datarecovery.ads.max.AdMaxInit.maxInitAction
import com.base.datarecovery.ads.max.AdMaxInterstitialUtils
import com.base.datarecovery.ads.max.AdMaxOpenUtils
import com.base.datarecovery.bean.ConstObject
import com.base.datarecovery.bean.ConstObject.ID_JUNK_CLEAN_PUSH
import com.base.datarecovery.bean.ConstObject.ID_PRIVACY_SPACE
import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_DOCUMENTS
import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_PHOTOS
import com.base.datarecovery.bean.ConstObject.ID_RECOVERY_VIDEOS
import com.base.datarecovery.bean.ConstObject.ID_SCREENSHOT_CLEAN
import com.base.datarecovery.bean.ConstObject.ID_SIMILAR_IMAGE
import com.base.datarecovery.bean.ConstObject.ifAgreePrivacy
import com.base.datarecovery.bean.ConstObject.isGuide
import com.base.datarecovery.bean.ConstObject.privacyPinPassword
import com.base.datarecovery.databinding.ActivitySplashBinding
import com.base.datarecovery.fcm.CloseNotificationReceiver
import com.base.datarecovery.fcm.CloseNotificationReceiver.Companion.NotificationId
import com.base.datarecovery.fcm.NotificationUtil
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.service.StayNotificationService.Companion.startStayNotification
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.random.Random

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

    private val TAG = "SplashActivity"
    private var job: Job? = null
    private val progress = MutableSharedFlow<Int>()
    private val progressFlow: SharedFlow<Int> = progress
    private var oneClickStart: Boolean = false
    private var actionId = -1


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

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        startStayNotification()
        NotificationUtil.stopNotificationHandler()

        actionId = intent?.extras?.getInt("actionId") ?: -1
        closeNotification()

        progressCollect()

        if (ifAgreePrivacy) {
            LogEx.logDebug(TAG, "ifAgreePrivacy=$ifAgreePrivacy")
            if (ConfigHelper.admobTrueMaxFlase) {
                LogEx.logDebug(TAG, "load admob")
                AdmobNativeUtils.loadNativeAd()
                AdmobInterstitialUtils.loadInterstitialAd(this)
            } else {
                LogEx.logDebug(TAG, "load max")
                maxInitAction = {
                    Log.d(TAG, "max init suc")
                    AdMaxOpenUtils.loadAppOpenAd(this)
                    AdMaxInterstitialUtils.loadInterstitialAd(this)
                    maxInitAction = null
                }
            }
            job = startProgress()
            binding.llStart.visibility = View.GONE
            binding.llProgress.visibility = View.VISIBLE
        } else {
            binding.llStart.visibility = View.VISIBLE
            binding.llProgress.visibility = View.GONE
        }

        val spannableString = SpannableString("Privacy Policy")
        spannableString.setSpan(
            UnderlineSpan(),
            0,
            spannableString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.idTvPrivacyPolicy.text = spannableString

        binding.idTvPrivacyPolicy.setOnClickListener {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse(ConfigHelper.privacyPolicy)
            )
            startActivity(intent)
        }


    }

    private fun progressCollect() {
        lifecycleScope.launch {
            progressFlow.collectLatest {
                if (it >= 100) {
                    job?.cancel()
                    jumpNext()
                    this.cancel()
                }
            }
        }
    }

    private fun jumpNext() {

        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                startActivity(Intent(this, ScanJunkActivity::class.java))
            }

            ID_SIMILAR_IMAGE -> {
                startActivity(Intent(this, RepeatActivity::class.java))
            }

            ID_SCREENSHOT_CLEAN -> {
                startActivity(Intent(this, ScreenShotActivity::class.java))
            }

            ID_RECOVERY_PHOTOS -> {
                startActivity(Intent(this, FileScanResultActivity::class.java).apply {
                    putExtra("ScanType", ConstObject.SCAN_PHOTOS)
                })
            }

            ID_RECOVERY_VIDEOS -> {
                startActivity(Intent(this, FileScanResultActivity::class.java).apply {
                    putExtra("ScanType", ConstObject.SCAN_VIDEOS)
                })
            }

            ID_RECOVERY_DOCUMENTS -> {
                startActivity(Intent(this, FileScanResultActivity::class.java).apply {
                    putExtra("ScanType", ConstObject.SCAN_DOCUMENTS)
                })
            }

            ID_PRIVACY_SPACE -> {
                if (privacyPinPassword.isNotEmpty()) {
                    startActivity(Intent(this, PrivacyPinOneActivity::class.java))
                } else {
                    startActivity(Intent(this, PrivacySpaceActivity::class.java).apply {

                    })
                }
            }

            else -> {
                val isHotLaunch = intent?.extras?.getBoolean("isHotLaunch", false) ?: false
                if (!isHotLaunch) {
                    if (!isGuide) {
                        startActivity(Intent(this@SplashActivity, GuideActivity::class.java))
                    } else {
                        startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                    }
                }
            }
        }
        finish()
    }

    private fun closeNotification() {
        sendBroadcast(Intent(this, CloseNotificationReceiver::class.java).apply {
            this.action = CloseNotificationReceiver.Action
            this.putExtra(NotificationId, actionId)
        })
    }

    override fun initListener() {

        binding.idTvStart.setOnClickListener {
            if (oneClickStart) {
                return@setOnClickListener
            }
            oneClickStart = true
            ifAgreePrivacy = true
            (application as MyApplication).initApp()
            if (ConfigHelper.admobTrueMaxFlase) {
                AdmobNativeUtils.loadNativeAd()
                AdmobInterstitialUtils.loadInterstitialAd(this)
            } else {
                maxInitAction = {
                    AdMaxOpenUtils.loadAppOpenAd(this)
                    AdMaxInterstitialUtils.loadInterstitialAd(this)
                }
            }
            binding.llStart.visibility = View.GONE
            binding.llProgress.visibility = View.VISIBLE
            job = startProgress()
        }
    }

    private var processTime = 0L
    private var outTimeAdStart = false
    private fun startProgress() = lifecycleScope.launch(Dispatchers.Main) {
        LogEx.logDebug(TAG, "startProgress")
        while (isActive) {
            val value = binding.pb.progress + 2
            binding.pb.setProgress(value, true)
            progress.emit(value)

            val delayTime = 450L
            delay(delayTime)
            processTime += delayTime
            if (processTime >= Random.nextLong(3000, 4000)) {
                if (!outTimeAdStart) {
                    outTimeAdStart = true
                    outTimeAd()
                }
            }
        }
    }


    private fun outTimeAd() {
        LogEx.logDebug(TAG, "outTimeAd")
        AdmobMaxHelper.admobMaxShowOpenAd(this, showBeforeAction = {
            job?.cancel()
        }) {
            binding.pb.progress = 100
            jumpNext()
        }
    }

    override fun onResume() {
        super.onResume()
        LogEx.logDebug(TAG, "onResume")
        if (ifAgreePrivacy && job?.isActive == false) {
            job = startProgress()
        }
    }

    override fun onPause() {
        super.onPause()
        job?.cancel()
        LogEx.logDebug(TAG, "onPause")
    }


}