package rallyedto

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 rallyedto.aluminiumedto.scanedto.Pleadedto.Companion.startJob
import rallyedto.battleedto.acresedto.Bellyedto
import rallyedto.battleedto.acresedto.Criticismedto
import rallyedto.battleedto.acresedto.Wageedto
import rallyedto.epicalyxedto.rodedto.trunkedto.Aisleedto
import rallyedto.epicalyxedto.rodedto.trunkedto.Scholaredto
import rallyedto.epicalyxedto.rodedto.trunkedto.winneredto.Addedto
import rallyedto.epicalyxedto.rodedto.trunkedto.winneredto.Countryedto
import rallyedto.epicalyxedto.rodedto.trunkedto.winneredto.Inhibitionedto
import rallyedto.finishedto.buriededto.ministryedto.Bleededto
import rallyedto.finishedto.complianceedto.minuteedto.Poundedto
import rallyedto.policeedto.huntedto.Snuggleedto.ifAgreePrivacy
import rallyedto.talledto.blewedto.Musicaledto
import rallyedto.talledto.blewedto.Pianoedto
import rallyedto.talledto.blewedto.Robedto
import rallyedto.talledto.blewedto.Teaedto
import rallyedto.talledto.blewedto.Trenchedto
import java.util.Calendar
import java.util.UUID
import java.util.concurrent.TimeUnit

class Columnedto : Criticismedto() {

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

    companion object {
        var isInterOpenShowing: Boolean = false

        @JvmField
        var PAUSED_VALUE = 0
        fun initApp() {
            (context as Columnedto).initApp()
        }
    }

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

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

    fun initApp() {
        uuid = Pianoedto.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            Pianoedto.getInstance().put("uuid", uuid)
        }
        FacebookSdk.sdkInitialize(applicationContext)
//            FacebookSdk.setIsDebugEnabled(true)
//            FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)
        val topic = GlobalConfig.PACKAGE_NAME + "_push"
        Scholaredto.initFirebase(this)
        Scholaredto.subscribeToTopic(topic)
        Musicaledto.logDebug(TAG, "topic=${topic}")
        Aisleedto.setupScreenStatusListener(this)
        Teaedto.init()
        Bellyedto.requestBlack()
        initLifeListener()
        Poundedto.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() ?: ""
                Pianoedto.getInstance().put("gid", gid)
            }
        }

    }

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

            override fun onActivityStarted(activity: Activity) {
                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {
                    val topActivity: Activity? = Trenchedto.topActivity
                    val flag = if (topActivity == null) {
                        true
                    } else {
                        Wageedto.noLoadingActivities.all {
                            !topActivity.localClassName.contains(
                                it,
                                true
                            )
                        }
                    }
                    if (flag) {
                        topActivity?.startActivity(
                            Intent(
                                topActivity,
                                Bleededto::class.java
                            ).apply {
                                putExtra("isHotLaunch", true)
                                putExtra("type", -1)
                            })
                    }
                }
                lastTimeResume = 0
            }

            override fun onActivityResumed(activity: Activity) {
                PAUSED_VALUE = 1
            }


            override fun onActivityPaused(activity: Activity) {
                PAUSED_VALUE = 2
                lastTimePause = System.currentTimeMillis()

            }

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

            }

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

            override fun onActivityDestroyed(activity: 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() )

                        Robedto.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, Addedto::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, Inhibitionedto::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, Inhibitionedto::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
        )
    }

}