package rowedto.jockeyedto.sheetedto

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.job.JobService
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 com.reyun.solar.engine.OnAttributionListener
import com.reyun.solar.engine.SolarEngineConfig
import com.reyun.solar.engine.SolarEngineManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject
import rowedto.jockeyedto.sheetedto.atticedto.equipmentedto.exactedto.costumeedto.Mythedto
import rowedto.jockeyedto.sheetedto.atticedto.fadeedto.Bottomedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.ifAgreePrivacy
import rowedto.jockeyedto.sheetedto.dryedto.stableedto.Biggestedto.Companion.startJob
import rowedto.jockeyedto.sheetedto.interactiveedto.twistedto.Constitutionedto
import rowedto.jockeyedto.sheetedto.interactiveedto.twistedto.Trouseredto
import rowedto.jockeyedto.sheetedto.interactiveedto.twistedto.feeedto.eveningedto.Handleedto
import rowedto.jockeyedto.sheetedto.interactiveedto.twistedto.feeedto.eveningedto.Plusedto
import rowedto.jockeyedto.sheetedto.interactiveedto.twistedto.feeedto.eveningedto.Undermineedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Celledto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Driededto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Performanceedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Atedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Slantedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Stewardedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Worthedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import java.util.Calendar
import java.util.UUID
import java.util.concurrent.TimeUnit

class Epicalyxedto : Driededto() {

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

    companion object {
        var isInterOpenShowing: Boolean = false

        @JvmField
        var PAUSED_VALUE = 0
    }

    override fun init() {
//        initUUid()
//        initApp()

        startJob()
        initLifeListener()
        solarInit()
        if (ifAgreePrivacy) {
            initApp()
        }
        startWorkManager()
        startAlarm()
        start48Alarm()
        start72Alarm()
    }

    fun initApp() {
        uuid = Stewardedto.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            Stewardedto.getInstance().put("uuid", uuid)
        }
        FacebookSdk.sdkInitialize(applicationContext)
//            FacebookSdk.setIsDebugEnabled(true)
//            FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)
        val topic = Celledto.packageName + "_push"
        Constitutionedto.initFirebase(this)
        Constitutionedto.subscribeToTopic(topic)
        Dishedto.logDebug(TAG, "topic=${topic}")
        Trouseredto.setupScreenStatusListener(this)
        Worthedto.init()
        Performanceedto.requestBlack()
        initLifeListener()
        Mythedto.requestWeatherData()
        //  startJob()


        if (ifAgreePrivacy) {

            MainScope().launch(Dispatchers.Main) {

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

    }

    fun startWorkManager() {
        // WorkManager.getInstance(this).cancelAllWorkByTag("ScannerWorker")
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            "ScannerWorker",
            ExistingPeriodicWorkPolicy.KEEP,
            PeriodicWorkRequestBuilder<Plusedto>(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?) {
                Atedto.addActivity(activity)
            }

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

                    val topActivity: Activity? = Atedto.topActivity

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

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

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

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

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


            override fun onActivityPaused(activity: Activity) {
//                Dishedto.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) {
                Atedto.removeActivity(activity)
            }
        })
    }

    private fun solarInit() {
        SolarEngineManager.getInstance().preInit(context, "f6b7345fd1edd658")
        val config = SolarEngineConfig.Builder()
            //  .logEnabled() //开启本地调试日志
            .build()
        SolarEngineManager.getInstance().initialize(
            context, "f6b7345fd1edd658", config
        ) { code ->
            if (code == 0) {
                //初始化成功
                config.setOnAttributionListener(object : OnAttributionListener {
                    override fun onAttributionSuccess(attribution: JSONObject) {
                        //获取归因结果成功时执行的动作
                        // Log.e("MXL", "onAttributionSuccess: "+attribution.toString() )

                        Slantedto.event("source_atrribute", ext = attribution)
                    }

                    override fun onAttributionFail(errorCode: Int) {
                        //获取归因结果失败时执行的动作
                        //   Log.e("MXL", "onAttributionFail: "+errorCode )
                    }
                })
            } else {
                //初始化失败，具体失败原因参考下方code码释义
            }
        }

    }

    fun startAlarm() {

        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, 1,
            Intent(this, Undermineedto::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1800000,
            pendingIntent
        )
    }

    fun start48Alarm() {
        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, 2,
            Intent(this, Handleedto::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1800000 * 2 * 48,
            pendingIntent
        )
    }

    fun start72Alarm() {
        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, 3,
            Intent(this, Handleedto::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1800000 * 2 * 72,
            pendingIntent
        )
    }

}