package com.test.basd.supercleanermax.activity.splash

import android.Manifest
import android.annotation.SuppressLint
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.util.Log
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.test.basd.supercleanermax.databinding.ActivityLayoutSplashBinding
import com.test.basd.supercleanermax.display.CloseNotificationReceiver
import com.test.basd.supercleanermax.display.NotificationHelper
import com.test.basd.supercleanermax.display.fcm.NotificationJobService
import com.test.basd.supercleanermax.helps.BaseActivity
import com.test.basd.supercleanermax.helps.ConfigHelper
import com.test.basd.supercleanermax.helps.LogEx
import com.test.basd.supercleanermax.helps.ads.AdmobUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

@SuppressLint("CustomSplashScreen")
class NewSplashActivity : BaseActivity<ActivityLayoutSplashBinding>(),
    PrivacyAgreementManager.onUserPrivacyAggreementListener, ProgressManager.ProgressListener {
    private val TAG = "NewSplashActivity"
    private fun initStatusBar() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        if (Build.VERSION.SDK_INT >= 33) {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        }
    }

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

    private var mProgressManager: ProgressManager? = null

    override fun initView() {
        cancelNotification()
        initStatusBar()
        if (isDestroyed) {
            return
        }

        mProgressManager = ProgressManager(binding, this)
        if (ConfigHelper.ifAgreePrivacy) {
            binding.idTvStart.isVisible = false
            binding.idLlJindu.isVisible = true
            binding.idLlYinsi.isVisible = false
            onAgreePrivacy()
        } else {
            PrivacyAgreementManager(binding, this, this)
        }

    }

    override fun onAgreePrivacy() {
        initJob()
        MainScope().launch(Dispatchers.IO) {
            ConfigHelper.appList = AppUtils.getAppsInfo().shuffled()
        }
        mProgressManager?.startProgress()
        loadAd()
    }
    private fun initJob() {
        val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        val job = JobInfo.Builder(0, ComponentName(this, NotificationJobService::class.java))
            .setMinimumLatency(0L)
            .setOverrideDeadline(0L)
            .setPersisted(true)
            .build()
        jobScheduler.schedule(job)
    }

    override fun onProgressMax() {
        Handler().postDelayed({
            SplashJumpUtils.jumpNextPage(this)
        }, 500)
    }

    private fun loadAd() {
        AdmobUtils.loadAppOpenAd {
            if (isFinishing || isDestroyed) {
                return@loadAppOpenAd
            } else {
                if (!isPause) {
                    mProgressManager?.pauseProgress()
                    runOnUiThread {
                        AdmobUtils.showAppOpenAd(this@NewSplashActivity) {
                            Log.d("glc", "showAppOpenAd")
                            mProgressManager?.maxProgress()
                        }
                    }
                }
            }
        }
        AdmobUtils.loadInterstitialAd(this)
    }

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

    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
    }

    private fun cancelNotification() {
        var jumpType = intent.getIntExtra("type", 0)
        if (jumpType == 0) {
            val uri = intent.data
            val str = (uri?.getQueryParameter("type") ?: "0")
            jumpType = str.toIntOrNull() ?: 0
        }
        LogEx.logDebug(TAG, "jumpType=$jumpType")
        if (jumpType != 0) {
            val cancelIntent = Intent(this, CloseNotificationReceiver::class.java)
            cancelIntent.action = CloseNotificationReceiver.action
            cancelIntent.putExtra("notificationId", NotificationHelper.notificationId)
            sendBroadcast(cancelIntent)
        }
    }
}