package de.wechselbild.wallpaper

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import java.util.concurrent.Executors

class WallpaperAlarmReceiver : BroadcastReceiver() {
  override fun onReceive(context: Context, intent: Intent) {
    if (!WallpaperStore.enabled(context)) {
      WallpaperScheduler.cancel(context)
      return
    }
    val applicationContext = context.applicationContext
    val result = goAsync()
    executor.execute {
      try {
        if (WallpaperScheduler.claimIfDue(applicationContext)) try {
          WallpaperStore.applyNext(applicationContext)
        } finally {
          WallpaperScheduler.scheduleNext(applicationContext)
        }
      } finally {
        WallpaperScheduler.ensureScheduled(applicationContext)
        WallpaperRotationService.rescheduleRunningService()
        result.finish()
      }
    }
  }

  companion object {
    private val executor = Executors.newSingleThreadExecutor()
  }
}
