// TODO: something is broken for the new mygame.p8.png
const imageDataToRom = (imageData: ImageData) => {
    const width = imageData.width;
    const height = imageData.height;
    const data = []; // For raw cart data

    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            const index = (y * width + x) * 4;
            const r = imageData.data[index];
            const g = imageData.data[index + 1];
            const b = imageData.data[index + 2];
            const a = imageData.data[index + 3];

            // Extracting and encoding the data from pixel components
            const byte = ((b & 3) << 0) | ((g & 3) << 2) | ((r & 3) << 4) | ((a & 3) << 6);
            data.push(byte);
        }
    }

    // At this point, `data` contains the raw bytes extracted from the image
    // Here, you would decode this data into a format representing the cart
    // This could involve uncompressing code, reading sprite data, etc.
    // The specifics depend on your cart format and how data was originally encoded

    // Returning raw data for demonstration; you'll need to adapt this part
    return data.slice(0, 32768);
    // return data.slice(0, 32768);
}

const pngGetImageData = (src: string) => {
	return new Promise<ImageData>((resolve, reject) => {
		try {
			const img = document.createElement('img');
			const canvas = document.createElement('canvas');
			const ctx = canvas.getContext('2d')!;
	
			img.onload = () => {
				canvas.width = img.width;
				canvas.height = img.height;
				ctx.drawImage(img, 0, 0);
				const imageData = ctx.getImageData(0, 0, img.width, img.height);
				resolve(imageData);
			};
            img.onerror = () => {
                reject(Error("BAD IMAGE"));
            }
			img.src = src;
		} catch (err) {
			reject(err);
		}
	})
}

export const pngToRom = async (src: string) => {
	return imageDataToRom(await pngGetImageData(src));
}