package com.zxhyis.toolss.ui.page

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.style.UnderlineSpan
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdUtils
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.ad.ConfigHelper
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.ad.bean.PushCfg
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.common.notification.AppService
import com.zxhyis.toolss.common.notification.NotificationBroadcast
import com.zxhyis.toolss.databinding.ActivityLayoutSplashBinding
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.startActivity
import com.zxhyis.toolss.ui.home.MainActivity
import com.zxhyis.toolss.ui.page.appmanager.AppManager2Activity
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity
import com.zxhyis.toolss.ui.page.notifaction.NotificationCleanActivity
import com.zxhyis.toolss.ui.page.notifaction.NotificationGuestActivity
import com.zxhyis.toolss.ui.page.photocompress.photo.StartCompressionPhotoActivity
import com.zxhyis.toolss.ui.page.recentusage.RecentAppActivity
import com.zxhyis.toolss.ui.page.speed.BatteryOptimizerActivity
import com.zxhyis.toolss.ui.page.speed.SpeedActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.concurrent.timer
import kotlin.random.Random

@SuppressLint("CustomSplashScreen")
class SplashActivity : TopActivity<ActivityLayoutSplashBinding>() {
    private val TAG = "SplashActivity"
    private var isgouxuan = true
    private var jump: Boolean = false
    override fun getViewBinding1(): ActivityLayoutSplashBinding {
        return ActivityLayoutSplashBinding.inflate(layoutInflater)
    }

    private var isPause = false

    override fun onStart() {
        super.onStart()
        isPause = false
    }

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

    override fun onResume() {
        super.onResume()
        isPause = false
    }

    override fun onStop() {
        super.onStop()
        isPause = true
    }

    override fun init() {
        val type = intent.getIntExtra("type", -1)
        if (type != -1) {
            NotificationBroadcast.cancelNotification(this)
        }

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        if (Build.VERSION.SDK_INT >= 33) {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        }
        vb.idTvStart.isVisible = true
        vb.idLlJindu.isVisible = false
        vb.idLlYinsi.isVisible = true

        if (ConfigHelper.ifAgreePrivacy) {
            vb.idTvStart.isVisible = false
            vb.idLlJindu.isVisible = true
            vb.idLlYinsi.isVisible = false
            loadAd()
        }

        vb.idTvStart.setOnClick(javaClass.simpleName) {
            if (true) {
                vb.idTvStart.isVisible = false
                vb.idLlJindu.isVisible = true
                vb.idLlYinsi.isVisible = false
                ConfigHelper.ifAgreePrivacy = true
                (application as FileApp).initApplication()
                loadAd()
            } else {
                ToastUtils.showShort("Please agree the terms to use App functions")
            }
        }

        vb.idImgGouxuan.setOnClick(javaClass.simpleName) {
            if (isgouxuan) {
                isgouxuan = false
                vb.idImgGouxuan.setImageResource(R.drawable.xuan)
            } else {
                isgouxuan = true
                vb.idImgGouxuan.setImageResource(R.drawable.gouxuan_border)
            }
        }
        vb.idUseTerms.setOnClick(javaClass.simpleName) {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse("https://sites.google.com/view/terms-select/home")
            )
            startActivity(intent)
        }

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

        vb.idTvPrivacyPolic.setOnClick(javaClass.simpleName) {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse("https://sites.google.com/view/clean-mas/home")
            )
            startActivity(intent)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            startForegroundService(Intent(this, AppService::class.java))
        } else {
            startService(Intent(this, AppService::class.java))
        }

    }

    private fun loadAd() {
        AdUtils.getLoadingTime()
        val loadTime = SPUtils.getInstance().getInt("loading_page_time")
        MainScope().launch(Dispatchers.Main) {
            launch(Dispatchers.IO) {
                ConfigHelper.appList = AppUtils.getAppsInfo().shuffled()
            }
            var time = 0
            while (true) {
                delay(200)
                time += 200
                if (vb.pb.progress <= 98 && time <= loadTime * 1000) {
                    vb.pb.progress = (vb.pb.progress + Random.nextInt(5)).coerceAtMost(98)
                } else if (vb.pb.progress != 99 && !isPause) {
                    break
                }
            }
            delay(50)
            vb.pb.progress = 100
            jumpNextPage()
        }



        AdmobUtils.loadAppOpenAd {
            timer(period = 300) {
                if (isFinishing || isDestroyed) {
                    cancel()
                } else if (vb.pb.progress > 0) {
                    vb.pb.progress = 99
                    if (!isPause) {
                        cancel()
                        runOnUiThread {
                            AdmobUtils.showAppOpenAd(this@SplashActivity) {
                                vb.pb.progress = 100
                            }
                        }
                    }
                }
            }
        }
        AdmobUtils.loadInterstitialAd(this)
        AdmobUtils.loadNativeAd()
    }

    private fun jumpNextPage() {
        if (isDestroyed or jump) {
            return
        }
        jump = true
        val JumpType = intent.getIntExtra("type", 0)
        LogEx.logDebug(TAG, "JumpType=$JumpType")
        when (JumpType) {
//=================================主动广播=======================================
            PushCfg.ID_JUNK_CLEAN_PUSH -> {
                startActivity<PrepareScanActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=PrepareScanActivity")
            }

            PushCfg.ID_VIRUS_PUSH -> {
                startActivity<VirusActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=VirusActivity")
            }

            PushCfg.ID_BIGFILE_PUSH -> {
                startActivity<BigFileCleanActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=BigFileCleanActivity")
            }

            PushCfg.ID_PHOTO_COMPRESS -> {
                startActivity<StartCompressionPhotoActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=StartCompressionPhotoActivity")
            }

            PushCfg.ID_APP_MANAGER -> {
                startActivity<AppManager2Activity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=AppManager2Activity")
            }

            PushCfg.ID_NETWORK_TRAFFIC -> {
                startActivity<NetWorkActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=NetWorkActivity")
            }

            PushCfg.ID_CLEAN_NOTIFICATION -> {
                if (SPUtils.getInstance().getBoolean("notification_guest", false)) {
                    startActivity(Intent(this, NotificationCleanActivity::class.java))
                    EventHelper.event("notification_jump", "JumpType=$JumpType activity=NotificationCleanActivity")
                } else {
                    startActivity(Intent(this, NotificationGuestActivity::class.java))
                    EventHelper.event("notification_jump", "JumpType=$JumpType activity=NotificationGuestActivity")
                }
            }

            PushCfg.ID_RECENT_USE_APP -> {
                startActivity<RecentAppActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=RecentAppActivity")
            }

            PushCfg.ID_SIMILAR_IMAGE -> {
                startActivity<RepeaterdPhotoActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=RepeaterdPhotoActivity")
            }

            PushCfg.ID_CLEAN_SPEAKER -> {
                startActivity<SpeakerCleanerActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=SpeakerCleanerActivity")
            }

            PushCfg.ID_BATTERY_OPTIMIZATION -> {
                startActivity<BatteryOptimizerActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=BatteryOptimizerActivity")
            }

//================================被动广播=========================================

            PushCfg.ID_INSTALL_PACKAGE_PUSH -> {
                startActivity<VirusActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=VirusActivity")
            }

            PushCfg.ID_UNINSTALL_PACKAGE_PUSH -> {
                startActivity<PrepareScanActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=PrepareScanActivity")
            }

            PushCfg.ID_CHARGE -> {
                startActivity<BatteryInfoActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=BatteryInfoActivity")
            }

            PushCfg.ID_LOW_BATTERY_PUSH -> {
                startActivity<BatteryInfoActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=BatteryInfoActivity")
            }

            PushCfg.ID_PHONE_ACCELERATE -> {
                startActivity<SpeedActivity>()
                EventHelper.event("notification_jump", "JumpType=$JumpType activity=SpeedActivity")
            }

            else -> {
                val isHotLaunch = intent?.extras?.getBoolean("isHotLaunch", false) ?: false
                if (!isHotLaunch) {
                    //  startActivity<StartPageActivity>()
                    startActivity<MainActivity>()
                }
            }
        }

        finish()
    }
}
