import { clearScreen, fillRect } from "./window.ts";
import { drawIcon, drawText } from "./builtins.ts";
import { COLOR } from "./colors.ts";
import { getSheet } from "./sheet.ts";
import { mouseClick, mousePos } from "./mouse.ts";
import { getCart } from "./cart.ts";
import { font } from "./font.ts";
import { codeIcon, spriteIcon, mapIcon } from "./icons.ts";
import { reGridWithGap } from "./util.ts";

const fontHeight = font.height;

export const page = {activeSheet: 0, tab: "sheet"};

const gridX = 8;
const gridY = 20;
const cellW = 22;
const cellH = 16;
const gapX = 8;
const gapY = 8;

const update = () => {
	if (mouseClick()) {
		const {x: mouseX, y: mouseY} = mousePos();
		const g = reGridWithGap(mouseX, mouseY, gridX, gridY, cellW, cellH, gapX, gapY);
		if (g) {
			const {x, y} = g;
			page.activeSheet = 4*y+x;
			const sheet = getSheet(page.activeSheet);
			if (!sheet) {
				console.log(x, y, g);
			}
			page.tab = getSheet(page.activeSheet).sheet_type;
		}
	}
}

const draw = () => {
	clearScreen();
	fillRect(0, 8, 128, 112, COLOR.DARKGRAY);

	// Draw the sheet grid
	getCart().forEach((sheet, i) => {
		const x = gridX+(cellW+gapX)*(i%4);
		const y = gridY+(cellH+gapY)*Math.floor(i/4);
		fillRect(x, y, cellW, cellH, i===page.activeSheet ? COLOR.PURPLE : COLOR.BLACK);
		drawText(x+(cellW)/2, y+(cellH-fontHeight)/2, i.toString().padStart(2,"0"));
		const icon = {
			code: codeIcon,
			spritesheet: spriteIcon,
			map: mapIcon,
			none: null,
		}[sheet.sheet_type];
		if (icon) {
			drawIcon(x+2, y+4, icon, COLOR.WHITE);
		}
	});
}

export const viewsheets = {
	update,
	draw,
}