import { getCart } from "./cart.ts";
import { LinearGrid } from "./util.ts";
// import { runCode, addToContext } from "./runcode.ts";

// "code" | "spritesheet" | "map" | "sfx" | "patterns" | "fonts"
export type Sheet = {
	sheet_type: "code",
	value: string,
} | {
	sheet_type: "spritesheet",
	value: Array<Array<number>>,
} | {
	sheet_type: "map",
	value: Array<[number, number]>,
} | {
	sheet_type: "none",
	value: null,
}
export type SheetType = Sheet["sheet_type"];

export const getSheet = (n: number): Sheet => {
	return getCart()[n];
}

// deno-lint-ignore no-explicit-any
export const setSheet = (n: number, type: SheetType, value: any) => {
	return getCart()[n] = {sheet_type: type, value};
}

export const getCodeSheet = (sheet: number) => {
	const {sheet_type, value} = getSheet(sheet);
	if (sheet_type !== "code") {
		throw "Trying to use a non-code sheet as code."
	}
	return value;
}

export const getSpriteSheet = (sheet: number) => {
	const {sheet_type, value} = getSheet(sheet);
	if (sheet_type !== "spritesheet") {
		throw Error("Trying to use a non-sprite sheet as a spritesheet.");
	}
	while (value.length < 128) {
		value.push(Array(64).fill(0));
	}
	return value;
}

export const getMapSheet = (sheet: number) => {
	const {sheet_type, value} = getSheet(sheet);
	if (sheet_type !== "map") {
		throw "Trying to use a non-map sheet as a map."
	}
	sheet_type
	return LinearGrid(value, 64);
}