package invalid.lena.rsend

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import java.util.concurrent.TimeUnit

// Scheduler keeps one periodic sync request aligned with the saved config.
object Scheduler {

    // Keep this distinct from the retired pre-0.1.3 one-time chain. WorkManager
    // persists unique names across app upgrades, so changing it creates a
    // second schedule and leaves the first one invisible to the UI.
    const val NAME = "periodic-sync-v2"
    private const val RETIRED_NAME = "periodic-sync"

    fun apply(ctx: Context) {
        val cfg = Config.load(ctx)
        val s = cfg.schedule
        val wm = WorkManager.getInstance(ctx)

        // Idempotently retire both the old one-time chain and any periodic job
        // created by the unreleased name regression.
        wm.cancelUniqueWork(RETIRED_NAME)

        if (!s.enabled || !cfg.syncReady(Keys.exists(ctx))) {
            wm.cancelUniqueWork(NAME)
            return
        }

        val constraints = Constraints.Builder()
            .setRequiredNetworkType(if (s.wifiOnly) NetworkType.UNMETERED else NetworkType.CONNECTED)
            .setRequiresCharging(s.requireCharging)
            .build()
        val req = PeriodicWorkRequestBuilder<SyncWorker>(
            s.intervalMinutes.toLong().coerceAtLeast(Schedule.MIN_INTERVAL_MINUTES.toLong()),
            TimeUnit.MINUTES,
        )
            .setConstraints(constraints)
            .build()
        wm.enqueueUniquePeriodicWork(NAME, ExistingPeriodicWorkPolicy.UPDATE, req)
    }
}
