package com.knecon.fforesight.service.layoutparser.processor.utils;

import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.iqser.red.service.redaction.v1.server.model.document.nodes.Page;

import lombok.experimental.UtilityClass;

@UtilityClass
public class BBoxMergingUtility {

    public Map<Page, Rectangle2D> mergeBBoxes(List<Map<Page, Rectangle2D>> bboxesToMerge) {

        Map<Page, Rectangle2D> bBoxPerPage = new HashMap<>();
        Set<Page> pages = bboxesToMerge.stream()
                .flatMap(map -> map.keySet()
                        .stream())
                .collect(Collectors.toSet());
        for (Page page : pages) {
            Rectangle2D bBoxOnPage = bboxesToMerge.stream()
                    .filter(childBboxPerPage -> childBboxPerPage.containsKey(page))
                    .map(childBboxPerPage -> childBboxPerPage.get(page))
                    .collect(RectangleTransformations.collectBBox());
            bBoxPerPage.put(page, bBoxOnPage);
        }
        return bBoxPerPage;
    }

}
