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

#include <nostalgia/core/core.hpp>

using namespace nostalgia;

static int spriteX = 72;
static int spriteY = 64;

static int updateHandler(core::Context *ctx) noexcept {
	int xmod = 0;
	int ymod = 0;
	if (core::buttonDown(ctx, core::GamePad_Right)) {
		xmod = 2;
	} else if (core::buttonDown(ctx, core::GamePad_Left)) {
		xmod = -2;
	}
	if (core::buttonDown(ctx, core::GamePad_Down)) {
		ymod = 2;
	} else if (core::buttonDown(ctx, core::GamePad_Up)) {
		ymod = -2;
	}
	if (!xmod && !ymod) {
		spriteX += 1;
	}
	spriteX += xmod;
	spriteY += ymod;
	constexpr auto s = "nostalgia";
	for (unsigned i = 0; s[i]; ++i) {
		const auto c = static_cast<unsigned>(s[i] - ('a' - 1));
		core::setSprite(ctx, i, static_cast<unsigned>(spriteX) + 8 * (i + 1), static_cast<unsigned>(spriteY), c);
	}
	return 16;
}

static void keyEventHandler(core::Context *ctx, core::Key key, bool down) noexcept {
	if (down && key == core::Key::Alpha_Q) {
		core::shutdown(ctx);
	}
}

ox::Error run(ox::UniquePtr<ox::FileSystem> fs) noexcept {
	oxRequireM(ctx, core::init(std::move(fs)));
	constexpr auto TileSheetAddr = "/TileSheets/Charset.ng";
	constexpr auto PaletteAddr = "/Palettes/Charset.npal";
	oxReturnError(core::loadSpriteTileSheet(ctx.get(), 0, TileSheetAddr, PaletteAddr));
	oxReturnError(core::initConsole(ctx.get()));
	core::puts(ctx.get(), 10, 9, "DOPENESS!!!");
	core::setUpdateHandler(ctx.get(), updateHandler);
	core::setKeyEventHandler(ctx.get(), keyEventHandler);
	return core::run(ctx.get());
}

