"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var Core = tslib_1.__importStar(require("@intelligentgraphics/ig.gfx.core"));
var ig_gfx_core_1 = require("@intelligentgraphics/ig.gfx.core");
var ig_gfx_threejs_1 = require("@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
 */
function restrictTransformationToBounds(transformation, constraints, componentId) {
    var planeSegment = ig_gfx_core_1.MathTypes.convertBoundsToXZPlaneSegment(constraints);
    var bounds = Core.State.API.GetBounds(componentId, "Local", false);
    var abb = new ig_gfx_threejs_1.AbstractBoundingBox();
    abb.setFromTransformation(transformation, bounds);
    var points = abb.getPoints().map(function (p) { return (tslib_1.__assign(tslib_1.__assign({}, p), { y: 0 })); });
    var outside = points.filter(function (p) { return !ig_gfx_core_1.LinearAlgebra.IsInsidePlaneSegment(planeSegment, p); });
    if (!outside || outside.length === 0) {
        return transformation;
    }
    var distances = outside.map(function (point) {
        return ig_gfx_core_1.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 = ig_gfx_core_1.LinearAlgebra.ProjectToPlaneSegment(planeSegment, furthestOutside);
    var moveBy = ig_gfx_core_1.Vector.Sub3(furthestOutside, projectedToBounds);
    return tslib_1.__assign(tslib_1.__assign({}, transformation), { position: ig_gfx_core_1.Vector.Sub3(transformation.position, moveBy) });
}
exports.restrictTransformationToBounds = restrictTransformationToBounds;
