#include <pebble.h>

#include "../../../engine/src/i18n.h"
#include "app_message.h"
#include "config.h"
#include "i18n_tables.h"
#include "notify.h"
#include "reading_state.h"
#include "ui_report_window.h"
#include "ui_text_window.h"

static WatchConfig s_config;

static void show_setup_required(void) {
  text_window_push(i18n_get("ui.setup_required_title", "Setup Required"),
                    i18n_get("ui.setup_required_body",
                             "Open this app's settings from the Pebble mobile app to add your "
                             "birth details, then reopen Deck in a Dash."));
}

static void on_config_updated(const WatchConfig *cfg) {
  bool was_configured = s_config.configured;
  s_config = *cfg;
  watch_i18n_load(s_config.lang);

  if (!s_config.configured) return;

  config_log(&s_config); /* the values this newly-recomputed reading is based on */
  reading_state_recompute(&s_config.birth, s_config.gender);
  notify_reschedule(&s_config); /* settings may have changed notify_enabled/hour/minute */
  if (was_configured) {
    report_window_reload();
  } else {
    report_window_push();
  }
}

/* Fires only if the scheduled wakeup goes off while this app is already
 * open (notify_was_wakeup_launch() below covers the far more common
 * case: the wakeup launching the app fresh). Refreshes the same way a
 * new day's config submission would, since the report window is already
 * on screen and the reading may now be for a new day. */
static void on_wakeup(WakeupId wakeup_id, int32_t cookie) {
  (void)wakeup_id;
  (void)cookie;
  vibes_double_pulse();
  if (!s_config.configured) return;
  reading_state_recompute(&s_config.birth, s_config.gender);
  report_window_reload();
  notify_reschedule(&s_config); /* wakeup_schedule() is one-shot - re-arm for tomorrow */
}

int main(void) {
  config_load(&s_config);
  watch_i18n_load(s_config.lang);
  app_message_init(on_config_updated);
  notify_subscribe(on_wakeup);

  config_log(&s_config); /* the values this session's reading (if any) is based on */

  if (s_config.configured) {
    reading_state_recompute(&s_config.birth, s_config.gender);
    report_window_push();
    notify_reschedule(&s_config); /* wakeup_schedule() is one-shot - re-arm on every launch */
    if (notify_was_wakeup_launch()) {
      vibes_double_pulse();
    }
  } else {
    show_setup_required();
  }

  app_event_loop();

  report_window_deinit();
}
