package com.zxhyis.toolss.logic.appstate

import android.annotation.SuppressLint
import android.app.usage.UsageEvents
import android.app.usage.UsageEvents.Event.ACTIVITY_STOPPED
import android.app.usage.UsageEvents.Event.STANDBY_BUCKET_CHANGED
import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Context
import android.os.Build
import androidx.lifecycle.LifecycleCoroutineScope
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.logic.TimeUtils.simpleDateFormat
import com.zxhyis.toolss.ui.page.viewmodel.AppViewModel
import com.zxhyis.toolss.ui.page.viewmodel.AppViewModel.Companion.timePair
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.LinkedList


object EventUtils {
    const val TAG = "EventUtils"

    @SuppressLint("SimpleDateFormat")
    private val dateFormat = SimpleDateFormat("M-d-yyyy HH:mm:ss")

    private fun printTime(startTime: Long, endTime: Long) {
        LogEx.logDebug(TAG, " EventUtils-getEventList()   Range start:$startTime")
        LogEx.logDebug(TAG, " EventUtils-getEventList()   Range end:$endTime")
        LogEx.logDebug(
            TAG,
            " EventUtils-getEventList()   Range start:" + dateFormat.format(startTime)
        )
        LogEx.logDebug(TAG, " EventUtils-getEventList()   Range end:" + dateFormat.format(endTime))
    }


    @SuppressLint("InlinedApi")
    fun getEventList(
        context: Context,
        startTime: Long,
        endTime: Long
    ): LinkedList<UsageEvents.Event> {
//        printTime(startTime, endTime)
        val mEventList = LinkedList<UsageEvents.Event>()
        val mUsmManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val events = mUsmManager.queryEvents(startTime, endTime)
        while (events.hasNextEvent()) {
            val event = UsageEvents.Event()
            events.getNextEvent(event)

            val flag1 = (event.eventType == UsageEvents.Event.ACTIVITY_RESUMED ||
                    event.eventType == UsageEvents.Event.ACTIVITY_PAUSED ||
                    event.eventType == UsageEvents.Event.ACTIVITY_STOPPED ||
                    event.eventType == UsageEvents.Event.FOREGROUND_SERVICE_START ||
                    event.eventType == UsageEvents.Event.FOREGROUND_SERVICE_STOP)

            val flag2 =
                event.eventType != ACTIVITY_STOPPED || event.eventType != STANDBY_BUCKET_CHANGED

            if (flag2) {
//                LogEx.logDebug(TAG, "event ${event.packageName} ${event.eventType}")
                mEventList.add(event)
            }
        }

        return mEventList
    }

    @SuppressLint("InlinedApi")
    fun getEventList2(
        context: Context,
        startTime: Long,
        endTime: Long,
    ): HashMap<String, ArrayList<UsageEvents.Event>> {

        printTime(startTime, endTime)
        val mUsmManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        //链表记录所有的Event.快速查找
        val allList = ArrayList<UsageEvents.Event>()

        try {
            val events = mUsmManager.queryEvents(startTime, endTime)
            while (events.hasNextEvent()) {
                val event = UsageEvents.Event()
                events.getNextEvent(event)

                val flag2 =
                    (event.eventType != ACTIVITY_STOPPED) && (event.eventType != STANDBY_BUCKET_CHANGED)
                if (flag2) {
                    allList.add(event)
                }
            }
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Exception ${e.printStackTrace()}")
            e.printStackTrace()
        }

        //记录数据结构
        val hashMap = HashMap<String, ArrayList<UsageEvents.Event>>()

        allList.forEachIndexed { index, event ->

            //例子：CCAAVCSAABBBCDEFGABCDEFAABB
            //过滤的结果
            //CAASAAGAFAA

            val list = hashMap[event.packageName]
            if (list == null) {
                hashMap[event.packageName] = arrayListOf()
            }

            //上个Event是否存在
            var lastEvent: UsageEvents.Event? = null
            val lastIndex = index - 1
            if (index > 0) {
                lastEvent = allList[lastIndex]
            }

            //上一个Event是否相同包
            if (lastEvent != null && lastEvent.packageName != event.packageName) {
                list?.add(lastEvent)
            }

            list?.add(event)

        }

        return hashMap
    }

    /**
     * 测试打印数据,数据量过大Log来不急打印
     */
    @SuppressLint("InlinedApi")
    fun printEventList(
        context: Context,
        lifecycleCoroutineScope: LifecycleCoroutineScope
    ): Deferred<Unit> {
        return lifecycleCoroutineScope.async(Dispatchers.IO) {
            val pair = timePair(AppViewModel.YESTERDAY_QUERY)
            val startTime: Long = pair.first
            val endTime: Long = pair.second

            printTime(startTime, endTime)
            val mUsmManager =
                context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
            //链表记录所有的Event.快速查找
            val allLinkedList = LinkedList<UsageEvents.Event>()

            try {
                var i = 0
                val events = mUsmManager.queryEvents(startTime, endTime)
                while (events.hasNextEvent()) {

                    val event = UsageEvents.Event()
                    events.getNextEvent(event)

                    val flag2 =
                        (event.eventType != ACTIVITY_STOPPED) && (event.eventType != STANDBY_BUCKET_CHANGED)
                    if (flag2) {
                        i++
                        allLinkedList.add(event)
                        LogEx.logDebug(
                            TAG, "$i event2 ${event.packageName} " +
                                    "${simpleDateFormat.format(event.timeStamp)} " +
                                    "${event.eventType}"
                        )
                        delay(1)
                    }

                }
            } catch (e: Exception) {
                LogEx.logDebug(TAG, "Exception ${e.printStackTrace()}")
                e.printStackTrace()
            }

            LogEx.logDebug(TAG, "allLinkedList.size=${allLinkedList.size}")
        }
    }


    /**
     * 前台运行App+后台运行App=总的启动App
     */
    fun getUsageList(context: Context, startTime: Long, endTime: Long): ArrayList<UsageStats> {
        val list = arrayListOf<UsageStats>()
        val mUsmManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val map = mUsmManager.queryAndAggregateUsageStats(startTime, endTime)
        map.values.forEach { stats ->
            if (stats.totalTimeInForeground > 0) {
                list.add(stats)
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    if (stats.totalTimeForegroundServiceUsed > 0) {
                        list.add(stats)
                    }
                }
            }

        }
        return list
    }
}
