package com.file.clean.q

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.tool.elite.battery.business.push.BadgeUtils
import com.file.clean.q.GlobalConfig.KEY_APP_BACKGROUND
import com.file.clean.q.GlobalConfig.KEY_INIT
import com.file.clean.q.GlobalConfig.KEY_INSTALL_TIME
import com.file.clean.q.GlobalConfig.KEY_SOLAR
import com.file.clean.q.GlobalConfig.KEY_UUID
import com.file.clean.q.business.BlacklistUtils
import com.file.clean.q.business.DeviceUtils
import com.file.clean.q.business.push.FirebaseUtils
import com.file.clean.q.business.InstallReferrerUtils
import com.file.clean.q.business.EventUtils
import com.file.clean.q.business.admob.AdmobManager
import com.file.clean.q.business.newAdmob.AdmobHelps
import com.file.clean.q.business.push.Alarm2Receiver
import com.file.clean.q.business.push.AlarmReceiver
import com.file.clean.q.business.push.MyWorker
import com.file.clean.q.business.push.NotificationJobService.Companion.startNotification
import com.file.clean.q.business.push.PackageReceiver
import com.file.clean.q.business.push.UnlockReceiver
import com.file.clean.q.util.SPUtils
import com.file.clean.q.view.activity.StartActivity
import com.file.clean.q.view.weather.WeatherUtils
import com.link.play.ad.LinkPlaySdk
import com.tool.elite.cleaner.utils.ActivityManagerUtils
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()

        LinkPlaySdk.isDebug(true)
        //接口配置
        //LinkPlaySdk.init(this,GlobalConfig.URL_API,GlobalConfig.PACKAGE_NAME,GlobalConfig.KEY_AES)
        LinkPlaySdk.init(this,"https://feedapihk.zhangxinhulian.com","com.unamzo.pdfreader.badcc","1qd6f41dgpjsep9t")

        guideSharedPreferences = getSharedPreferences("ButtonSP", MODE_PRIVATE)
    }

    private fun init() {
        startNotification()
        InstallReferrerUtils.init()
//        BlacklistUtils.requestBlacklist { AdmobManager.blacklist = it }
        BlacklistUtils.requestBlacklist { AdmobHelps.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(context)
        UnlockReceiver.register(context)
    }
    fun getGuideSharedPreferences(): SharedPreferences? {
        return guideSharedPreferences
    }
    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)
            }
        })
    }
}