import { __assign } from "tslib";
import * as Core from "@intelligentgraphics/ig.gfx.core";
import { LinearAlgebra, Vector, MathTypes, } from "@intelligentgraphics/ig.gfx.core";
import { AbstractBoundingBox } from "@intelligentgraphics/ig.gfx.threejs";
/**
 * To restrict the transformation of an object to the given bounds,
 * we will calculate the point that is furthest outside of the bounds
 * and bring it back inside by translation.
 * This algorithm assumes that the passed bounds are inside the xz-plane,
 * e.g. that the y-component of the constraints is 0
 */
export function restrictTransformationToBounds(transformation, constraints, componentId) {
    var planeSegment = MathTypes.convertBoundsToXZPlaneSegment(constraints);
    var bounds = Core.State.API.GetBounds(componentId, "Local", false);
    var abb = new AbstractBoundingBox();
    abb.setFromTransformation(transformation, bounds);
    var points = abb.getPoints().map(function (p) { return (__assign(__assign({}, p), { y: 0 })); });
    var outside = points.filter(function (p) { return !LinearAlgebra.IsInsidePlaneSegment(planeSegment, p); });
    if (!outside || outside.length === 0) {
        return transformation;
    }
    var distances = outside.map(function (point) {
        return LinearAlgebra.DistanceToPlaneSegment(planeSegment, point);
    });
    var maxDistanceValue = 0;
    var maxDistanceIdx = 0;
    for (var idx = 0; idx < distances.length; idx++) {
        if (distances[idx] > maxDistanceValue) {
            maxDistanceIdx = idx;
            maxDistanceValue = distances[idx];
        }
    }
    var furthestOutside = outside[maxDistanceIdx];
    var projectedToBounds = LinearAlgebra.ProjectToPlaneSegment(planeSegment, furthestOutside);
    var moveBy = Vector.Sub3(furthestOutside, projectedToBounds);
    return __assign(__assign({}, transformation), { position: Vector.Sub3(transformation.position, moveBy) });
}
