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

const gridX = 8;
const gridY = 40;
const cellW = 8;
const cellH = 8;
const gapX = 8;
const gapY = 8;

const sheetTypes = ["code", "spritesheet", "map"] as const;
const defaultSheetVal = {
	code: () => "",
	spritesheet: () => Array(64).fill(0).map(() => Array(64).fill(0)),
	map: () => Array(64*64).fill(0).map(() => [0, 0]),
	none: () =>null,
}

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: _y} = g;
			const sheetType = sheetTypes[x];
			setSheet(page.activeSheet, sheetType, defaultSheetVal[sheetType]());
			page.tab = getSheet(page.activeSheet).sheet_type;
		}
	}
}
const draw = () => {
	clearScreen();
	useSpritesheet(page.activeSheet);
	fillRect(0, 8, 128, 112, COLOR.BLACK);

	drawText(4, 16, "Click an icon below to choose");
	drawText(4, 16+7, "this sheet's type...");

	// Draw the spritesheet
	sheetTypes.forEach((sheetType, i) => {
		const sx = gridX+(cellW+gapX)*(i%6);
		const sy = gridY+(cellH+gapY)*Math.floor(i/6);
		const icon = {
			code: codeIcon,
			spritesheet: spriteIcon,
			map: mapIcon,
			none: null,
		}[sheetType];
		drawIcon(sx, sy, icon, COLOR.BLUE);
	});
}

export const nonetab = {
	update,
	draw,
}