package importantedto

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 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.Rideredto
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.Braidedto
import importantedto.growedto.umbrellaedto.butterflyedto.fraudedto.toweredto.Leftedto
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 org.json.JSONObject
import java.util.Calendar
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()

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

    fun initApp() {
        uuid = Waitedto.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            Waitedto.getInstance().put("uuid", uuid)
        }
            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)
            }
        })
    }
    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() )

                        Rideredto.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, Braidedto::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, Leftedto::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, Leftedto::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
        )
    }

}