#include "notify.h"

/* Only one kind of wakeup event exists in this app, so the cookie value
 * itself carries no information - it exists only because
 * wakeup_schedule()/wakeup_get_launch_event() require one. */
#define NOTIFY_WAKEUP_COOKIE 0

void notify_reschedule(const WatchConfig *cfg) {
  wakeup_cancel_all();
  if (!cfg->notify_enabled) return;

  time_t now = time(NULL);
  struct tm target_tm = *localtime(&now);
  target_tm.tm_hour = cfg->notify_hour;
  target_tm.tm_min = cfg->notify_minute;
  target_tm.tm_sec = 0;

  time_t target = mktime(&target_tm);
  if (target <= now) target += SECONDS_PER_DAY; /* today's time already passed */

  WakeupId id = wakeup_schedule(target, NOTIFY_WAKEUP_COOKIE, true);
  if (id < 0) {
    APP_LOG(APP_LOG_LEVEL_ERROR, "notify: wakeup_schedule failed: %d", (int)id);
  }
}

bool notify_was_wakeup_launch(void) {
  return launch_reason() == APP_LAUNCH_WAKEUP;
}

void notify_subscribe(WakeupHandler handler) {
  wakeup_service_subscribe(handler);
}
