Pith - spline
package com.vgmlr.spline

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
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 kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class SplineJob : JobService() {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    override fun onStartJob(params: JobParameters): Boolean {
        val ctx = applicationContext
        scope.launch {
            val ok = SplineRepo.scan(ctx)
            if (ok) {
                val entries = SplineRepo.entries(ctx, SplineRepo.cached(ctx))
                val n = SplineRepo.updates(entries)
                if (SplinePrefs.notifyOn(ctx)) SplineNotify.post(ctx, n)
                if (!SplineBadge.visible) SplineBadge.apply(ctx, n > 0)
            }
            jobFinished(params, !ok)
        }
        return true
    }

    override fun onStopJob(params: JobParameters): Boolean = true

    override fun onDestroy() {
        scope.cancel()
        super.onDestroy()
    }
}

internal object SplineSchedule {
    private const val JOB = 1

    fun apply(ctx: Context, interval: SplineInterval) {
        val js = ctx.getSystemService(JobScheduler::class.java)
        if (interval == SplineInterval.NONE) {
            js.cancel(JOB)
            return
        }
        val cur = js.getPendingJob(JOB)
        if (cur != null && cur.intervalMillis == interval.ms) return
        js.schedule(
            JobInfo.Builder(JOB, ComponentName(ctx, SplineJob::class.java))
                .setPeriodic(interval.ms)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build()
        )
    }
}

internal object SplineNotify {
    private const val CHANNEL = "updates"
    private const val ID = 1

    fun post(ctx: Context, count: Int) {
        val nm = ctx.getSystemService(NotificationManager::class.java)
        if (count <= 0) {
            nm.cancel(ID)
            return
        }
        if (!nm.areNotificationsEnabled()) return
        nm.createNotificationChannel(
            NotificationChannel(CHANNEL, "Updates", NotificationManager.IMPORTANCE_DEFAULT)
        )
        val open = PendingIntent.getActivity(
            ctx,
            0,
            Intent(ctx, MainActivity::class.java)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val n = Notification.Builder(ctx, CHANNEL)
            .setSmallIcon(R.drawable.ic_notify)
            .setColor(ctx.getColor(R.color.notify))
            .setContentTitle("Spline")
            .setContentText(if (count == 1) "1 Update" else "$count Updates")
            .setContentIntent(open)
            .setAutoCancel(true)
            .build()
        nm.notify(ID, n)
    }

    fun clear(ctx: Context) {
        ctx.getSystemService(NotificationManager::class.java).cancel(ID)
    }
}