import { clearScreen, fillRect } from "./window.ts";
import { codetab } from "./codetab.ts";
import { spritetab } from "./spritetab.ts";
import { viewsheets, page } from "./viewsheets.ts";
import { COLOR } from "./colors.ts";
import { mouseClick, mousePos } from "./mouse.ts";
import { drawIcon } from "./builtins.ts";
import { inRect } from "./util.ts";
import { sheetsIcon, trashIcon } from "./icons.ts";
import { SheetType, setSheet } from "./sheet.ts";
import { nonetab } from "./nonetab.ts";
import { maptab } from "./maptab.ts";

type TabName = SheetType; // "code" | "sprite" | "map" | "sfx" | "music" | "sheet";

const buttons: Array<{update: () => void, draw: () => void}> = [];
const makeTabButton = (tabname: TabName | "sheet", x: number, y: number, icon: Array<number>) => {
	buttons.push({
		update() {
			if (mouseClick()) {
				const {x: mouseX, y: mouseY} = mousePos();
				if (inRect(mouseX, mouseY, x, y, 8, 8)) {
					page.tab = tabname;
				}
			}
		},
		draw() {
			drawIcon(x, y, icon, page.tab === tabname ? COLOR.YELLOW : COLOR.WHITE);
		}
	})
}

const makeTrashButton = (x: number, y: number, icon: Array<number>) => {
	buttons.push({
		update() {
			if (page.tab !== "sheet") {
				return
			}
			if (mouseClick()) {
				const {x: mouseX, y: mouseY} = mousePos();
				if (inRect(mouseX, mouseY, x, y, 8, 8)) {
					setSheet(page.activeSheet, "none", null);
					page.tab = "sheet";
				}
			}
		},
		draw() {
			if (page.tab !== "sheet") {
				return
			}
			drawIcon(x, y, icon, COLOR.BLACK);
		}
	})
}

makeTabButton("sheet", 120, 0, sheetsIcon);
makeTrashButton(0, 0, trashIcon);

const update = () => {
	buttons.forEach(button => button.update());
	if (page.tab === "code") {
		codetab.update();
	} else if (page.tab === "spritesheet") {
		spritetab.update();
	} else if (page.tab === "map") {
		maptab.update();
	} else if (page.tab === "sheet") {
		viewsheets.update();
	} else if (page.tab === "none") {
		nonetab.update();
	}
}

const draw = () => {
	clearScreen();
	if (page.tab === "code") {
		codetab.draw();
	} else if (page.tab === "spritesheet") {
		spritetab.draw();
	} else if (page.tab === "map") {
		maptab.draw();
	} else if (page.tab === "sheet") {
		viewsheets.draw();
	} else if (page.tab === "none") {
		nonetab.draw();
	}
	fillRect(0, 0, 128, 8, COLOR.RED);
	fillRect(0, 120, 128, 8, COLOR.RED);
	buttons.forEach(button => button.draw());
}

export const editmode = {
	update,
	draw,
}