/**
 *
 * @param {number} subject_v0
 * @param {number} subject_v1
 * @param {number} bounds_v0
 * @param {number} bounds_v1
 * @returns {number} displacement for subject to fit into bounds
 */
function interval_force_into_bounds(
    subject_v0, subject_v1,
    bounds_v0, bounds_v1
){

    let displacement = 0;

    const bounds_span = bounds_v1 - bounds_v0;

    const subject_span = subject_v1 - subject_v0;

    if(bounds_span >= subject_span) {
        // fits

        if (subject_v0 < bounds_v0) {
            displacement = bounds_v0 - subject_v0;
        } else if (subject_v1 > bounds_v1) {
            displacement = bounds_v1 - subject_v1;
        }

    }else{
        // too big to fit, shift so subject covers the entire bounds

        const a = subject_v0 - bounds_v0;
        const b = bounds_v1 - subject_v1;

        if(a > 0){
            // subject left edge is inside bounds, shift left so it covers
            displacement = -a;
        }else if(b > 0){
            // subject right edge is inside bounds, shift right so it covers
            displacement = b;
        }
    }

    return displacement;
}

/**
 *
 * @param {AABB2} container
 * @param {AABB2} box
 */
export function aabb2_force_into_container(container, box) {

    const dX = interval_force_into_bounds(box.x0, box.x1, container.x0, container.x1);
    const dY = interval_force_into_bounds(box.y0, box.y1, container.y0, container.y1);

    box.move(dX, dY);
}