import { Transform } from "konva/lib/Util";
import { DC, EntityShape } from "../deconstruction";


export const shapeTreeEq = (
	parent: EntityShape,
	eq: (shape: EntityShape) => boolean,
	checked: EntityShape[] = []
) => {
	if (checked.includes(parent)) return null;
	if (eq(parent)) {
		return parent;
	}

	if ("children" in parent) {
		for (const child of parent.children) {
			const e = shapeTreeEq(child, eq, checked);
			if (e) {
				return child;
			}
		}
	}

	return null;
};

export const shapeParentsEq = (
	target: EntityShape,
	eq: (shape: EntityShape) => boolean,
	checked: EntityShape[] = []
) => {
	while (target) {
		if (checked.includes(target)) return null;
		if (eq(target)) {
			return target;
		}
		target = target.parent as any;
	}
	return null;
};

export const shapeTreeContain = (
	parent: EntityShape | EntityShape[],
	target: EntityShape,
	checked: EntityShape[] = []
) => {
	const eq = Array.isArray(parent)
		? (shape: EntityShape) => parent.includes(shape)
		: (shape: EntityShape) => parent === shape;
	return shapeParentsEq(target, eq, checked);
};


export const setShapeTransform = (shape: EntityShape, transform: Transform) => {
	const config = transform.decompose()
	for (const key in config) {
		(shape as any)[key]((config as any)[key])
	}
}

export const packShape = <T extends EntityShape>(shape: T): DC<T> => ({
	getNode: () => shape,
	getStage: () => shape
})