import simpleSpawn from "async-spawner";
import tempy from "tempy";

// usage: node ./lib/calculate-perspective-coefficients.js demo.jpg 0 0 0 0 0 3024 -206 1292    4040 3024   4024 3316    4040 0  4040 0

type point = [number, number];

type pair = [point, point];
type transform_points = [pair, pair, pair, pair];

async function getCoefsForPerspective(file: string, points: transform_points) {
	const args = [
		"-verbose",
		file,
		"-virtual-pixel",
		"Transparent",
		"-distort",
		"perspective",
		points
			.map((pair) => pair.map((point) => point.join(",")).join(" "))
			.join("  "),
		"target.jpg",
	];
	const result = await simpleSpawn("convert", args);
	console.log(args);
	return result.stderr
		.split("\n")
		.slice(3, 5)
		.join(" ")
		.replace(/'/g, "")
		.split(",")
		.map((s) => parseFloat(s.trim()));
}

async function run() {
	const path = process.argv[2];
	const input_points = process.argv;
	input_points.shift();
	input_points.shift();
	input_points.shift();
	input_points.map(parseFloat);
	const parsed_points = [];
	const parsed_reverse_points = [];
	for (let i = 0; i <= 3; i++) {
		parsed_points.push([
			[input_points[i * 4 + 0], input_points[i * 4 + 1]],
			[input_points[i * 4 + 2], input_points[i * 4 + 3]],
		]);
		parsed_reverse_points.push([
			[input_points[i * 4 + 2], input_points[i * 4 + 3]],
			[input_points[i * 4 + 0], input_points[i * 4 + 1]],
		]);
	}
	const [forward, backward] = await Promise.all([
		getCoefsForPerspective(
			path,
			(parsed_points as unknown) as transform_points
		),
		getCoefsForPerspective(
			path,
			(parsed_reverse_points as unknown) as transform_points
		),
	]);
	console.log({ forward, backward });
}

run();
