package importantedto

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.facebook.FacebookSdk
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import importantedto.admireedto.sweptedto.Differenceedto
import importantedto.afteredto.constitutionaledto.Assumeedto
import importantedto.afteredto.constitutionaledto.Interferenceedto
import importantedto.afteredto.constitutionaledto.Neckedto
import importantedto.appliededto.surgeonedto.promiseedto.dialectedto.Styleedto
import importantedto.concreteedto.cameedto.Hateedto.ifAgreePrivacy
import importantedto.gallonedto.Rocketedto
import importantedto.gallonedto.Timetableedto
import importantedto.gallonedto.Tumbleedto
import importantedto.gallonedto.Waitedto
import importantedto.growedto.umbrellaedto.Correctionedto
import importantedto.growedto.umbrellaedto.Wakeedto
import importantedto.growedto.umbrellaedto.butterflyedto.fraudedto.toweredto.Merchantedto
import importantedto.igneousedto.fulledto.saladedto.Rescueedto.Companion.startJob
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.UUID
import java.util.concurrent.TimeUnit

class Exhibitionedto : Interferenceedto() {

    private val TAG = "MyApplication"
    var uuid = ""

    companion object {
        var isInterOpenShowing: Boolean = false

        @JvmField
        var PAUSED_VALUE = 0
    }

    override fun init() {
//        initUUid()
//        initApp()
      //  startStayNotification()
        initLifeListener()
//        solarInit()
        if(ifAgreePrivacy){
            initApp()
        }
        startWorkManager()
//        startAlarm()
//        start48Alarm()
//        start72Alarm()
    }

    private fun initUUid() {
        uuid = Waitedto.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            Waitedto.getInstance().put("uuid", uuid)
        }
    }

    fun initApp() {

            FacebookSdk.sdkInitialize(applicationContext)
//            FacebookSdk.setIsDebugEnabled(true)
//            FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)
            val topic = Neckedto.packageName + "_push"
            Correctionedto.initFirebase(this)
            Correctionedto.subscribeToTopic(topic)
            Tumbleedto.logDebug(TAG, "topic=${topic}")
            Wakeedto.setupScreenStatusListener(this)
            Timetableedto.init()
            Assumeedto.requestBlack()
            initLifeListener()
            startJob()


        if (ifAgreePrivacy) {

            MainScope().launch(Dispatchers.Main) {

                val deferred = async(Dispatchers.IO) {
                    try {
                        AdvertisingIdClient.getAdvertisingIdInfo(context).id
                    } catch (_: Exception) {
                        "unknown"
                    }
                }
                val gid = deferred.await() ?: ""
                Waitedto.getInstance().put("gid", gid)
            }
        }

    }
    fun startWorkManager(){
        // WorkManager.getInstance(this).cancelAllWorkByTag("ScannerWorker")
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            "ScannerWorker",
            ExistingPeriodicWorkPolicy.KEEP,
            PeriodicWorkRequestBuilder<Merchantedto>(15, TimeUnit.MINUTES)
                .setConstraints(
                    Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
                )
                .addTag("ScannerWorker")
                .build()
        )
    }


    private var lastTimePause = 0L
    private var lastTimeResume = 0L

    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 1500) {
            return true
        }
        return false
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun initLifeListener() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            private var count = 0
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                Rocketedto.getInstance().addActivity(activity)
            }

            override fun onActivityStarted(activity: Activity) {
//                Tumbleedto.logDebug(TAG, "onActivityStarted")
                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {

                    val topActivity: Activity? = Rocketedto.getInstance().topActivity

                    var flag = if (topActivity == null) {
                        true
                    } else {
                        Neckedto.noLoadingActivities.all {
                            !topActivity.localClassName.contains(it, true)
                        }
                    }

                    if (activity.localClassName.contains("AppLovinFullscreenActivity")) {
                        flag = false
                    }
                    Tumbleedto.logDebug(TAG, "flag=$flag" + "   activity:" + activity.localClassName)

                    if (flag && !isInterOpenShowing) {
                        if (Differenceedto.isOpenAdLoaded()) {

                            topActivity?.startActivity(
                                Intent(
                                    topActivity,
                                    Styleedto::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                    putExtra("type", -1)
                                })
                        } else {
                            topActivity?.startActivity(
                                Intent(
                                    topActivity,
                                    Styleedto::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                    putExtra("type", -1)
                                })
                        }
                    }
                }
                lastTimeResume = 0
            }

            override fun onActivityResumed(activity: Activity) {
//                Tumbleedto.logDebug(TAG, "onActivityResumed")
                PAUSED_VALUE = 1
            }


            override fun onActivityPaused(activity: Activity) {
//                Tumbleedto.logDebug(TAG, "onActivityPaused")
                PAUSED_VALUE = 2
                lastTimePause = System.currentTimeMillis()

            }

            override fun onActivityStopped(activity: Activity) {
                count--
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {
                Rocketedto.getInstance().removeActivity(activity)
            }
        })
    }


}