import simpleSpawn, { deferedSpawn } from "async-spawner";
import { promises as fs } from "fs";
import path from "path";
import AbortablePromise from "../../abortable-promise/@types";
import { alprMultiPersp, alpr_response } from "./alpr";

async function run(): Promise<void> {
	const gui = await deferedSpawn("python", [
		"/home/kuba/projects/personal/qml-player/main.py",
		"/home/kuba/projects/personal/qml-player/template.qml",
	]);
	const dir = "/home/kuba/projects/personal/zgłaszańska/03-20_2/";
	const files = await fs.readdir(dir);
	let multi_perp_promise: AbortablePromise<alpr_response> | null = null;
	for (const file of files.filter((f) => f.includes("jpg"))) {
		const full_path = path.resolve(dir, file);
		if (multi_perp_promise) {
			multi_perp_promise.abort();
		}
		multi_perp_promise = alprMultiPersp(full_path);
		multi_perp_promise
			.then((o) => {
				if (o === null) return;
				console.log("Got coords!");
				const { img_width, img_height } = o;
				if (o.results.length) {
					console.log(o.results[0]);
					const min_x = Math.min(
						...o.results[0].coordinates.map((c: any) => c.x)
					);
					const max_x = Math.max(
						...o.results[0].coordinates.map((c: any) => c.x)
					);
					const min_y = Math.min(
						...o.results[0].coordinates.map((c: any) => c.y)
					);
					const max_y = Math.max(
						...o.results[0].coordinates.map((c: any) => c.y)
					);

					// console.log({
					// 	rect_x: min_x / img_width,
					// 	rect_y: min_y / img_height,
					// 	rect_width: (max_x - min_x) / img_width,
					// 	rect_height: (max_y - min_y) / img_height,
					// 	rect_text: o.results[0].candidates[0].plate,
					// });
					gui.write(
						JSON.stringify({
							rect_x: min_x / img_width,
							rect_y: min_y / img_height,
							rect_width: (max_x - min_x) / img_width,
							rect_height: (max_y - min_y) / img_height,
							rect_text: o.results[0].candidates[0].plate,
						})
					);
				} else {
					gui.write(JSON.stringify({ rect_width: 0 }));
				}
			})
			.catch(console.error);
		gui.write(
			JSON.stringify({
				current_image: full_path,
			})
		);
		let input: any;
		do {
			const raw_event = (await gui.waitForNextData()) as string;
			console.log(raw_event);
			input = JSON.parse(raw_event);
		} while (input.type !== "next");
	}
}

run().catch(console.error);
