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

#include <nostalgia/core/gfx.hpp>
#include <nostalgia/core/media.hpp>

#include "gfx.hpp"

namespace nostalgia::core {

ox::Error initConsole(Context *ctx) noexcept {
	constexpr auto TilesheetAddr = "/TileSheets/Charset.ng";
	constexpr auto PaletteAddr = "/Palettes/Charset.npal";
	setBgStatus(ctx, 0b0001);
	setBgCbb(ctx, 0, 0);
	return loadBgTileSheet(ctx, 0, TilesheetAddr, PaletteAddr);
}

ox::Error loadSpriteTileSheet(Context*,
                              unsigned,
                              const ox::FileAddress&,
                              const ox::FileAddress&) noexcept {
	return OxError(0);
}

ox::Error loadBgTileSheet(Context *ctx,
                          unsigned cbb,
                          const ox::FileAddress &tilesheetPath,
                          const ox::FileAddress &palettePath) noexcept {
	oxRequire(tilesheet, readObj<CompactTileSheet>(ctx, tilesheetPath));
	oxRequire(palette, readObj<Palette>(ctx, palettePath ? palettePath : tilesheet->defaultPalette));
	const unsigned bytesPerTile = tilesheet->bpp == 8 ? 64 : 32;
	const auto tiles = tilesheet->pixels.size() / bytesPerTile;
	constexpr int width = 8;
	const int height = 8 * static_cast<int>(tiles);
	ox::Vector<uint32_t> pixels;
	if (bytesPerTile == 64) { // 8 BPP
		pixels.resize(tilesheet->pixels.size());
		for (std::size_t i = 0; i < tilesheet->pixels.size(); ++i) {
			pixels[i] = toColor32(palette->colors[tilesheet->pixels[i]]);
		}
	} else { // 4 BPP
		pixels.resize(tilesheet->pixels.size() * 2);
		for (std::size_t i = 0; i < tilesheet->pixels.size(); ++i) {
			pixels[i * 2 + 0] = toColor32(palette->colors[tilesheet->pixels[i] & 0xF]);
			pixels[i * 2 + 1] = toColor32(palette->colors[tilesheet->pixels[i] >> 4]);
		}
	}
	renderer::loadBgTexture(ctx->rendererData<void>(), cbb, pixels.data(), width, height);
	return OxError(0);
}

void puts(Context *ctx, int column, int row, const char *str) noexcept {
	for (int i = 0; str[i]; ++i) {
		setTile(ctx, 0, column + i, row, static_cast<uint8_t>(charMap[static_cast<uint8_t>(str[i])]));
	}
}

}
