package com.swiftcleaner.chovey

import android.app.Activity
import android.app.AlarmManager
import android.app.Application
import android.app.PendingIntent
import android.app.job.JobService
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.bumptech.glide.Glide
import com.reyun.solar.engine.OnAttributionListener
import com.reyun.solar.engine.SolarEngineConfig
import com.reyun.solar.engine.SolarEngineManager
import com.swiftcleaner.chovey.GlobalConfig.KEY_APP_BACKGROUND
import com.swiftcleaner.chovey.GlobalConfig.KEY_INIT
import com.swiftcleaner.chovey.GlobalConfig.KEY_INSTALL_TIME
import com.swiftcleaner.chovey.GlobalConfig.KEY_SOLAR
import com.swiftcleaner.chovey.GlobalConfig.KEY_UUID
import com.swiftcleaner.chovey.business.BlacklistUtils
import com.swiftcleaner.chovey.business.DeviceUtils
import com.swiftcleaner.chovey.business.EventUtils
import com.swiftcleaner.chovey.business.InstallReferrerUtils
import com.swiftcleaner.chovey.business.admob.AdmobManager
import com.swiftcleaner.chovey.business.push.Alarm2Receiver
import com.swiftcleaner.chovey.business.push.AlarmReceiver
import com.swiftcleaner.chovey.business.push.FirebaseUtils
import com.swiftcleaner.chovey.business.push.MyWorker
import com.swiftcleaner.chovey.business.push.NotificationJobService.Companion.startNotification
import com.swiftcleaner.chovey.business.push.PackageReceiver
import com.swiftcleaner.chovey.business.push.UnlockReceiver
import com.swiftcleaner.chovey.util.SPUtils
import com.swiftcleaner.chovey.view.activity.StartActivity
import com.tool.elite.battery.business.push.BadgeUtils
import com.swiftcleaner.chovey.view.function.constellation.ActivityManagerUtils
import com.swiftcleaner.chovey.view.function.weather.WeatherUtils
import org.json.JSONObject
import java.util.Calendar
import java.util.UUID
import java.util.concurrent.TimeUnit


class CleanApplication : Application() {

    companion object {
        lateinit var context: CleanApplication
        var APP_STATE = 0

        fun init() {
            context.init()
        }

        fun startNotification() {
            context.startNotification()
        }
    }

    private var guideSharedPreferences: SharedPreferences? = null
    override fun onCreate() {
        super.onCreate()
        context = this
        WeatherUtils.requestWeatherData()
        DeviceUtils.init()
        registerActivityLifecycle()

        if (SPUtils.getInstance().getString(KEY_UUID).isEmpty())
            SPUtils.getInstance().putString(KEY_UUID, UUID.randomUUID().toString() + System.currentTimeMillis())

        if (SPUtils.getInstance().getLong(KEY_INSTALL_TIME) == 0L)
            SPUtils.getInstance().putLong(KEY_INSTALL_TIME, System.currentTimeMillis())

        if (SPUtils.getInstance().getBoolean(KEY_INIT)) init()
        Thread { Glide.get(this).clearDiskCache() }.start()

        guideSharedPreferences = getSharedPreferences("ButtonSP", MODE_PRIVATE)
    }

    fun getGuideSharedPreferences(): SharedPreferences? {
        return guideSharedPreferences
    }
    private fun init() {
        startNotification()
        InstallReferrerUtils.init()
        BlacklistUtils.requestBlacklist { AdmobManager.blacklist = it }
        initSolar()
        initFirebase()
        initAlarm(1, 1800000, AlarmReceiver::class.java)
        initAlarm(2, 1800000 * 2 * 48, Alarm2Receiver::class.java)
        initAlarm(3, 1800000 * 2 * 72, Alarm2Receiver::class.java)
        initWorkManager()
//        BatteryReceiver.register(this)
        PackageReceiver.register(this)
        UnlockReceiver.register(this)
    }

    private fun initSolar() {
        SolarEngineManager.getInstance().preInit(this, KEY_SOLAR)
        val config = SolarEngineConfig.Builder().build()
        SolarEngineManager.getInstance().initialize(this, KEY_SOLAR, config) { code ->
            if (code == 0) {
                config.setOnAttributionListener(object : OnAttributionListener {
                    override fun onAttributionSuccess(p0: JSONObject?) {
                        Log.d("TAG", "onAttributionSuccess: 获取归因结果成功 $p0   ")
                        EventUtils.event("source_atrribute", ext = p0)
                    }

                    override fun onAttributionFail(p0: Int) {
                        Log.d("TAG", "onAttributionSuccess: 获取归因结果失败  $p0  ")
                        EventUtils.event("source_atrribute_error")
                    }
                })
            }
        }
    }

    private fun initFirebase() {
        FirebaseUtils.initFirebase(this)
        val topic = "${packageName}_push"
        FirebaseUtils.subscribeToTopic(topic) {
            EventUtils.event("FCM_Topic_${topic}")
        }
        FirebaseUtils.getToken {
            val json = JSONObject()
            json.put("token", it)
            EventUtils.event("fcm_message_received", ext = json)
            SPUtils.getInstance().putString("token", it)
        }
    }

    private fun initAlarm(code: Int, intervalMillis: Long, cls: Class<*>) {
        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, code,
            Intent(this, cls),
            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,
            intervalMillis,
            pendingIntent
        )
    }

    private fun initWorkManager() {
        val tag = "${packageName}_unique_periodic_work"
        val periodicRequest = PeriodicWorkRequestBuilder<MyWorker>(15, TimeUnit.MINUTES)
            .setConstraints(
                Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
            )
            .addTag(tag)
            .build()
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            tag,
            ExistingPeriodicWorkPolicy.KEEP,
            periodicRequest)
    }

    private var lastTimePause = 0L
    private var lastTimeResume = 0L
    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 5000) {
            return true
        }
        return false
    }

    private fun registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            private var count = 0

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                ActivityManagerUtils.add(activity)
            }

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

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

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

            override fun onActivityStopped(activity: Activity) {
                count--
                if (count == 0) {
                    BadgeUtils.setBadgeNum(context, 1)
                }
            }

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

            override fun onActivityDestroyed(activity: Activity) {
                ActivityManagerUtils.remove(activity)
            }
        })
    }
}