/*
 * Copyright 2016 - 2022 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#include <nostalgia/core/config.hpp>
#include <nostalgia/core/core.hpp>

#include "addresses.hpp"
#include "bios.hpp"
#include "irq.hpp"
#include "core.hpp"

namespace nostalgia::core {

extern volatile gba_timer_t g_timerMs;
gba_timer_t g_wakeupTime;
UpdateHandler g_updateHandler = nullptr;

ox::Error run(Context *ctx) noexcept {
	g_wakeupTime = 0;
	while (ctx->running) {
		if (g_wakeupTime <= g_timerMs && g_updateHandler) {
			auto sleepTime = g_updateHandler(ctx);
			if (sleepTime >= 0) {
				g_wakeupTime = g_timerMs + static_cast<unsigned>(sleepTime);
			} else {
				g_wakeupTime = ~gba_timer_t(0);
			}
		}
		if constexpr(config::GbaEventLoopTimerBased) {
			// wait for timer interrupt
			nostalgia_core_intrwait(0, Int_timer0 | Int_timer1 | Int_timer2 | Int_timer3);
		} else {
			nostalgia_core_vblankintrwait();
		}
	}
	return OxError(0);
}

}
