import { Transform } from "konva/lib/Util";
import { vector, Pos } from "./math.ts";

/**
 * 创建对齐端口矩阵
 * @param targetView 目标窗口左上右下坐标
 * @param originView 源窗口左上右下坐标
 * @param retainScale 是否固定xy的缩放系数
 * @param padding 留白区域
 * @returns
 */
export const alignPortMat = (
	targetView: Pos[],
	originView: Pos[],
	retainScale = false,
	padding: Pos | number = 0
) => {
	padding = typeof padding === "number" ? { x: padding, y: padding } : padding;

	const pad = vector(padding);
	const real = vector(originView[1]).sub(originView[0]);
	const screen = vector(targetView[1]).sub(targetView[0]);
	const scale = screen.clone().sub(pad.multiplyScalar(2)).divide(real);

	if (retainScale) {
		scale.x = scale.y = Math.min(scale.x, scale.y); // 选择较小的比例以保持内容比例
	}

	const offset = screen
		.clone()
		.sub(real.clone().multiply(scale))
		.divideScalar(2)
		.sub(real.clone().multiply(scale));

	return new Transform().translate(offset.x, offset.y).scale(scale.x, scale.y);
};
