package com.zxhyis.toolss.ui.page.viewmodel

import android.annotation.SuppressLint
import android.app.usage.UsageEvents
import android.app.usage.UsageEvents.Event.ACTIVITY_PAUSED
import android.app.usage.UsageEvents.Event.ACTIVITY_RESUMED
import android.app.usage.UsageStats
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import androidx.lifecycle.ViewModel
import com.zxhyis.toolss.logic.AppBean
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.logic.TimeUtils
import com.zxhyis.toolss.logic.appstate.AppSizeUtils
import com.zxhyis.toolss.logic.appstate.EventUtils.getEventList2
import com.zxhyis.toolss.logic.appstate.EventUtils.getUsageList

class AppViewModel : ViewModel() {

    private val TAG = "AppViewModel"

    companion object {
        val PAST_60_MINUS_QUERY = 5
        val TODAY_QUERY = 15
        val YESTERDAY_QUERY = 25
        val SEVEN_DAYS_QUERY = 55
        val THIRTY_DAYS_QUERY = 65

        fun timePair(queryTime: Int): Pair<Long, Long> {
            return when (queryTime) {
                PAST_60_MINUS_QUERY -> TimeUtils.recent60Minutes()
                TODAY_QUERY -> TimeUtils.todayTimestamps()
                YESTERDAY_QUERY -> TimeUtils.yesterdayTimestamps()
                SEVEN_DAYS_QUERY -> TimeUtils.sevenDaysTimestamps()
                THIRTY_DAYS_QUERY -> TimeUtils.thirtyDaysTimestamps()
                else -> Pair(0, 0)
            }
        }
    }


    fun isLaunchApp(context: Context, app: PackageInfo, filterSystem: Boolean = true): Boolean {

        val flagSystem = (app.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) < 1
        val flag = if (filterSystem) flagSystem else true

        return flag && app.applicationInfo.packageName != context.packageName
    }

    fun setAppInstallTime(appBean: AppBean, context: Context) {
        //安装时间
        var firstInstallTime = 0L
        try {
            val packageManager = context.packageManager
            val packageInfo: PackageInfo = packageManager.getPackageInfo(appBean.pkg, 0)
            //应用装时间
            firstInstallTime = packageInfo.firstInstallTime
            //应用最后一次更新时间
            val lastUpdateTime = packageInfo.lastUpdateTime
//                        LogEx.logDebug(TAG, "lastUpdateTime=$lastUpdateTime")
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }

        appBean.installTime = firstInstallTime
    }

    /**
     * 设置使用大小
     */
    fun setAppBeanSize(context: Context, dataList: List<AppBean>) {
        dataList.forEach { app ->
            val size = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppSizeUtils.instance?.getAppSizeO(context, app.pkg)
            } else {
                AppSizeUtils.instance?.getAppSize(context, app.pkg)
            }
            app.appSize = size ?: 0
        }

    }

    /**
     * 设置最近使用时间
     */
    @SuppressLint("SimpleDateFormat")
    fun setAppLastUseTime(
        context: Context,
        dataList: List<AppBean>,
        queryTime: Int = THIRTY_DAYS_QUERY
    ) {

        val pair = timePair(queryTime)
        val startTime: Long = pair.first
        val endTime: Long = pair.second

        val usageList = getUsageList(context, startTime, endTime)
//        usageList.forEach { usage ->
//            LogEx.logDebug(TAG, "usage  pkg=${usage.packageName} lastTimeUsed=${usage.lastTimeUsed}")
//        }

        dataList.forEach { app ->
            val filterList = usageList.filter { it.packageName == app.pkg }
            app.usageStats = filterList
            app.lastUsedTime = if (filterList.isNotEmpty()) filterList.maxOf { it.lastTimeUsed } else -2//默认30天没数据
        }
    }

    /**
     * 设置最近使用分析数据
     */
    fun getAppUseAnalyze(
        context: Context,
        queryTime: Int = YESTERDAY_QUERY,
        dataList: List<AppBean>,
    ): ArrayList<AppBean> {
        val launchList = arrayListOf<AppBean>()
        val pair = timePair(queryTime)
        val startTime: Long = pair.first
        val endTime: Long = pair.second

        val stateList = getUsageList(context, startTime, endTime)
        val evenMap = getEventList2(context, startTime, endTime)

//        evenList.forEach { event -> printEvent(event) }
//        stateList.forEach { state -> printState(state) }

        dataList.forEach { app ->
            //这里只使用后台启动数据
            //FOREGROUND_SERVICE_START 19
            app.usageEvents = evenMap[app.pkg]?.filter { it.eventType == 19 }
            app.usageStats = stateList.filter { it.packageName == app.pkg }
        }

        launchList.addAll(dataList)

        return launchList
    }

    /**
     *
     * ACTIVITY_RESUMED 1
     * ACTIVITY_PAUSED 2
     * CONFIGURATION_CHANGE,
     * USER_INTERACTION,
     * STANDBY_BUCKET_CHANGED,
     * FOREGROUND_SERVICE_START,
     * FOREGROUND_SERVICE_STOP,
     * ACTIVITY_STOPPED
     */
    @SuppressLint("InlinedApi")
    private fun printEvent(event: UsageEvents.Event) {
        LogEx.logDebug(
            TAG, "even ${event.packageName} " +
                    "ACTIVITY_RESUMED=" + "${event.eventType == ACTIVITY_RESUMED} " +
                    "ACTIVITY_PAUSED=" + "${event.eventType == ACTIVITY_PAUSED} "
        )
    }

    @SuppressLint("NewApi")
    fun printState(state: UsageStats) {
        LogEx.logDebug(
            TAG, "state packageName=${state.packageName} " +
                    "${state.totalTimeInForeground} " +
                    "${state.totalTimeForegroundServiceUsed}"
        )
    }

    fun printAppDean(appBean: AppBean) {
        LogEx.logDebug(
            TAG, "appBean pkg=${appBean.pkg} "
        )
    }
}