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

#include <nostalgia/core/gfx.hpp>

#include <nostalgia/scene/scene.hpp>

namespace nostalgia::scene {

Scene::Scene(SceneStatic const&sceneStatic) noexcept:
	m_sceneStatic(sceneStatic) {
}

ox::Error Scene::setupDisplay(core::Context &ctx) const noexcept {
	if (m_sceneStatic.palettes.empty()) {
		return OxError(1, "Scene has no palettes");
	}
	auto const&palette = m_sceneStatic.palettes[0];
	oxReturnError(core::loadBgTileSheet(ctx, 0, m_sceneStatic.tilesheet));
	oxReturnError(core::loadBgPalette(ctx, 0, palette));
	// disable all backgrounds
	core::setBgStatus(ctx, 0);
	for (auto layerNo = 0u; auto const&layer : m_sceneStatic.tileMapIdx) {
		setupLayer(ctx, layer, layerNo);
		++layerNo;
	}
	return {};
}

void Scene::setupLayer(
		core::Context &ctx,
		ox::Vector<uint16_t> const&layer,
		unsigned layerNo) const noexcept {
	core::setBgStatus(ctx, layerNo, true);
	core::setBgCbb(ctx, layerNo, 0);
	auto x = 0;
	auto y = 0;
	const auto width = m_sceneStatic.rows[layerNo];
	for (auto const&tile : layer) {
		const auto tile8 = static_cast<uint8_t>(tile);
		core::setBgTile(ctx, layerNo, x, y, tile8);
		core::setBgTile(ctx, layerNo, x + 1, y, tile8 + 1);
		core::setBgTile(ctx, layerNo, x, y + 1, tile8 + 2);
		core::setBgTile(ctx, layerNo, x + 1, y + 1, tile8 + 3);
		x += 2;
		if (x >= width * 2) {
			x = 0;
			y += 2;
		}
	}
}

}
