package de.wechselbild.wallpaper

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.SystemClock

object WallpaperScheduler {
  private const val PREFS = "wechselbild"
  private const val KEY_NEXT_TRIGGER = "next_rotation_elapsed"
  private const val REQUEST_CODE = 4218

  fun ensureScheduled(context: Context) {
    if (!WallpaperStore.enabled(context)) {
      cancel(context)
      return
    }
    val now = SystemClock.elapsedRealtime()
    val storedTrigger = preferences(context).getLong(KEY_NEXT_TRIGGER, 0L)
    if (storedTrigger <= now) scheduleNext(context)
  }

  fun remainingDelay(context: Context): Long {
    val trigger = preferences(context).getLong(KEY_NEXT_TRIGGER, 0L)
    return (trigger - SystemClock.elapsedRealtime()).coerceAtLeast(0L)
  }

  @Synchronized
  fun claimIfDue(context: Context): Boolean {
    val preferences = preferences(context)
    val trigger = preferences.getLong(KEY_NEXT_TRIGGER, 0L)
    if (trigger <= 0L || trigger > SystemClock.elapsedRealtime() + 1_000L) return false
    preferences.edit().putLong(KEY_NEXT_TRIGGER, Long.MAX_VALUE).commit()
    return true
  }

  fun scheduleNext(context: Context) {
    val minutes = WallpaperStore.intervalMinutes(context)
    if (minutes <= 0) {
      cancel(context)
      return
    }
    val trigger = SystemClock.elapsedRealtime() + minutes * 60_000L
    val alarmManager = context.getSystemService(AlarmManager::class.java)
    val operation = operation(context)
    if (Build.VERSION.SDK_INT >= 23) {
      alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, trigger, operation)
    } else {
      alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, trigger, operation)
    }
    preferences(context).edit().putLong(KEY_NEXT_TRIGGER, trigger).apply()
  }

  fun cancel(context: Context) {
    context.getSystemService(AlarmManager::class.java).cancel(operation(context))
    preferences(context).edit().remove(KEY_NEXT_TRIGGER).apply()
  }

  private fun operation(context: Context) = PendingIntent.getBroadcast(
    context,
    REQUEST_CODE,
    Intent(context, WallpaperAlarmReceiver::class.java),
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
  )

  private fun preferences(context: Context) =
    context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
