/**
 * Remove all rectangles that are fully contained within others
 * @param {QuadTreeNode} boxes
 */
export function removeRedundantBoxes(boxes) {
    const removals = [];


    let datum;

    /**
     *
     * @param {QuadTreeDatum} intersection
     */
    function visitDatumIntersection(intersection) {
        if (datum === intersection) {
            //skip self
            return;
        }

        const ax0 = intersection.x0;
        const ay0 = intersection.y0;
        const ax1 = intersection.x1;
        const ay1 = intersection.y1;

        const bx0 = datum.x0;
        const by0 = datum.y0;
        const bx1 = datum.x1;
        const by1 = datum.y1;

        //question is now whether it is containment
        if (ax0 >= bx0 && ax1 <= bx1 && ay0 >= by0 && ay1 <= by1) {
            //b contains a
            removals.push(intersection);
        } else if (bx0 >= ax0 && bx1 <= ax1 && by0 >= ay0 && by1 <= ay1) {
            //a contains b
            removals.push(datum);

            //scheduled removal of the datum, prevent further traversal
            return false;
        }
    }

    /**
     *
     * @param {QuadTreeNode} node
     */
    function visitTreeNode(node) {
        const data = node.data;
        const dataCount = data.length;

        for (let i = 0; i < dataCount; i++) {
            /**
             *
             * @type {QuadTreeDatum}
             */
            datum = data[i];

            node.traverseRectangleIntersections(datum.x0, datum.y0, datum.x1, datum.y1, visitDatumIntersection);
        }
    }

    boxes.traversePreOrder(visitTreeNode);

    for (let i = 0; i < removals.length; i++) {
        const removal = removals[i];
        removal.disconnect();
    }
}
