package com.xhly.manageapp.workmanager

import android.app.usage.UsageEvents
import android.app.usage.UsageStatsManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.xhly.corelib.network.RetrofitService
import com.xhly.corelib.utils.AppUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.toFormat
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.log.LogAppStartBean
import com.xhly.manageapp.network.log.LogService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.util.Calendar

/**
 * 用来记录应用使用时长的定时任务
 */
class TimingWorker(context: Context, workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    private val serviceScope = CoroutineScope(MainScope().coroutineContext)
    override fun doWork(): Result {
        val result: Result = Result.success()
        val logService = RetrofitService.create<LogService>()
        serviceScope.launch {
            val appInfo = getAppInfo()
            if (appInfo.size > 0) {
                logService.postLogAppStartAdd(appInfo)
            }
        }
        return result
    }

    private fun getAppInfo(): ArrayList<LogAppStartBean> {
        //统计使用时长
        val dataList = AppUtils.GetAppList(applicationContext)
        val instance = Calendar.getInstance()
        instance.set(Calendar.MILLISECOND, 0)
        val timeInMillis = instance.timeInMillis - 1000 * 60 * 5
        val usageManager =
            applicationContext.getSystemService(AppCompatActivity.USAGE_STATS_SERVICE) as UsageStatsManager
        val startList = arrayListOf<LogAppStartBean>()
        var sn = ManageApplication.getDeviceInfo()
        if (usageManager != null) {
            val endTime = System.currentTimeMillis()
            val startTime = timeInMillis
            //queryEvents查询使用时长，时间范围设置后，返回的数据时间范围和设置的一致，但需要自己判断时长
            val queryEvents = usageManager.queryEvents(startTime, endTime)
            val event = UsageEvents.Event()

            while (queryEvents.hasNextEvent()) {
                queryEvents.getNextEvent(event)
                when (event.eventType) {
                    UsageEvents.Event.ACTIVITY_RESUMED -> {
                        val appStartBean = LogAppStartBean()
                        val first =
                            dataList.firstOrNull { event.packageName.equals(it.packageName) }
                        first?.let {
                            sn?.let {
                                appStartBean.sn=sn
                            }
                            appStartBean.appName = first.name
                            appStartBean.appPackage = first.packageName
                            appStartBean.starttime = event.timeStamp.toFormat()
                            appStartBean.ltype = 1
                            appStartBean.versionName = first.versionName
                            appStartBean.versionNum = first.versionNum
                            startList.add(appStartBean)
                        }
                    }

                    UsageEvents.Event.ACTIVITY_PAUSED -> {
                        val appStartBean = LogAppStartBean()
                        var first =
                            dataList.firstOrNull { event.packageName.equals(it.packageName) }
                        first?.let {
                            sn?.let {
                                appStartBean.sn=sn
                            }
                            appStartBean.appName = first.name
                            appStartBean.appPackage = first.packageName
                            appStartBean.starttime = event.timeStamp.toFormat()
                            appStartBean.ltype = 2
                            appStartBean.versionName = first.versionName
                            appStartBean.versionNum = first.versionNum
                            startList.add(appStartBean)
                        }
                    }
                }
            }
        }
        return startList
    }

    override fun onStopped() {
        super.onStopped()
        try {
            serviceScope.cancel()
        } catch (e: Exception) {

        }
    }
}