package app.furmeet.events.system.notification

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import app.furmeet.events.system.helper.getPendingJobCompat
import app.furmeet.events.system.helper.setPeriodicCompat
import app.furmeet.events.system.helper.setRequiresBatteryNotLowCompat
import app.furmeet.events.system.schedule.managers.RemoteAssetsHolder

class AppJobScheduler(context: Context) {
    init {
        RemoteAssetsHolder.ensureIsBuilt(context)
        val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        // notification
        if (jobScheduler.getPendingJobCompat(1) == null) {
            jobScheduler.schedule(
                    JobInfo.Builder(
                            1,
                            ComponentName(context, NotificationJobService::class.java)
                    )
                            .setPeriodicCompat(15 * 60 * 1000L, 5 * 60 * 1000L)
                            .setRequiresBatteryNotLowCompat(false)
                            .setPersisted(true)
                            .build()
            )
        }
        // schedule updater
        if (jobScheduler.getPendingJobCompat(2) == null) {
            jobScheduler.schedule(
                    JobInfo.Builder(
                            2,
                            ComponentName(context, ScheduleUpdaterJobService::class.java)
                    )
                            .setPeriodicCompat(15 * 60 * 1000L, 5 * 60 * 1000L)
                            .setRequiresBatteryNotLowCompat(false)
                            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                            .setPersisted(true)
                            .build()
            )
        }
    }

    companion object {
        fun runNow(context: Context) {
            val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            jobScheduler.schedule(
                    JobInfo.Builder(101, ComponentName(context, NotificationJobService::class.java))
                            .setMinimumLatency(1000L)
                            .setOverrideDeadline(1000L)
                            .build()
            )
            jobScheduler.schedule(
                    JobInfo.Builder(102, ComponentName(context, ScheduleUpdaterJobService::class.java))
                            .setMinimumLatency(1000L)
                            .setOverrideDeadline(1000L)
                            .build()
            )
        }
    }
}