package com.test.basd.smartjunkcleaner.display.fcm

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.job.JobParameters
import android.app.job.JobService
import android.content.Intent
import android.os.Build
import com.test.basd.smartjunkcleaner.display.NotificationService


@SuppressLint("SpecifyJobSchedulerIdRange")
class NotificationJobService : JobService() {
    private var isServiceRunning = false

    override fun onStartJob(params: JobParameters): Boolean {
        if (!isServiceRunning) {
            // 创建一个启动服务的Intent
            val intent = Intent(this, NotificationService::class.java)

            // 检查服务是否已经运行
            isServiceRunning = if (isServiceRunning(intent)) {
                true
            } else {
                // 启动服务
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent)
                } else {
                    startService(intent)
                }
                // 标记服务已经运行
                true
            }
        }
        // 告诉系统任务已完成
        jobFinished(params, false)
        return false
    }

    override fun onStopJob(params: JobParameters): Boolean {
        return false
    }

    private fun isServiceRunning(intent: Intent): Boolean {
        val manager: ActivityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val infos: List<ActivityManager.RunningServiceInfo> = manager.getRunningServices(Int.MAX_VALUE)
        for (info in infos) {
            if (info.service.className == intent.component?.className) {
                return true
            }
        }
        return false
    }

    companion object {
        private const val JOB_ID = 123
    }
}