import init, { dctify, resize } from './pkg/image_similarity.js';

async function run() {
	await init();
}
run();
const resizeWorker = new Worker("resize.js", { type: 'module' });

let imageContainers = document.getElementsByClassName("image-original");
let resizedImageContainer = document.getElementById("image-resize");
let dctCoefficientContainer = document.getElementById("image-dct");
let formImage = document.getElementById("dctimage");

let resizedBuffer = null;

// Resets all containers, deletes images, etc
// Redefines the event handlers for the base image
function reset() {
	//imageContainers.forEach((imageContainer) => {
	for (let imageContainer of imageContainers) {
		imageContainer.replaceChildren();
	}
	resizedImageContainer.replaceChildren();
	dctCoefficientContainer.replaceChildren();
	document.getElementById("resize").classList.remove("resize");
}

// Uses the resized buffer to get DCT coefficients
function getDCT() {
	let buf = new Uint8Array(resizedBuffer)
	let dct = dctify(buf);

	for (const c of dct) {
		let cdiv = document.createElement("div");
		cdiv.innerHTML = c.toFixed(1);
		dctCoefficientContainer.appendChild(cdiv);
	}
}

// Result from the resize worker, means we get resized buffer
resizeWorker.onmessage = function (e) {
	console.log(e.data);
	resizedBuffer = e.data.buffer;
	const resizedImage = document.createElement("img");
	resizedImage.src = URL.createObjectURL(
		new Blob([resizedBuffer], { type: 'image/png' })
	);
	resizedImageContainer.appendChild(resizedImage);

	// Set the width of the image explictly to help with the animation
	let image = document.getElementById("resize-original").children[0];
	image.width = image.width;
	image.height = image.height;
}

document.getElementById("resize-button").addEventListener("click", function() {
	document.getElementById("resize").classList.add("resize");
});

// User selected an image from disk. Start the demo.
formImage.addEventListener("change", function() {
	reset();
	// Should only get one file from picker
	for (const file of formImage.files) {
		let originalUrl = URL.createObjectURL(file);
		for (let imageContainer of imageContainers) {
			let originalImage = document.createElement("img");
			originalImage.src = originalUrl;
			imageContainer.appendChild(originalImage);
		}

		file.arrayBuffer().then((buf) => {
			buf = new Uint8Array(buf);
			resizeWorker.postMessage(buf);
		});
	}

	// Show the rest of the demo.
	document.getElementById("demo-resize").classList.add("visible");
});