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

import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.util.LinkedList;
import java.util.List;

import com.knecon.fforesight.service.layoutparser.processor.model.GapInformation;
import com.knecon.fforesight.service.layoutparser.processor.model.LineInformation;
import com.knecon.fforesight.service.layoutparser.processor.model.text.TextPositionSequence;

import lombok.experimental.UtilityClass;

@UtilityClass
public class InvisibleTableDetectionService {

    public List<List<Rectangle2D>> detectTable(List<TextPositionSequence> textPositionSequences, Rectangle2D tableBBox) {

        LineInformation lineInformation = LineDetectionService.calculateLineInformation(textPositionSequences);
        GapInformation gaps = GapDetectionService.findGapsInLines(textPositionSequences, tableBBox);
        List<Rectangle2D> gapsAcrossLines = GapsAcrossLinesService.detectXGapsAcrossLines(gaps, tableBBox);
        List<Double> columnXCoords = gapsAcrossLines.stream().map(RectangularShape::getCenterX).toList();
        int colCount = gapsAcrossLines.size();
        int rowCount = lineInformation.getLineBBox().size();
        List<List<Rectangle2D>> cells = new LinkedList<>();
        List<Rectangle2D> cellsInLine = new LinkedList<>();
        cells.add(cellsInLine);
        double x1;
        double y1;
        double x2;
        double y2;
        for (int col = 0; col < colCount + 1; col++) {
            for (int row = 0; row < rowCount + 1; row++) {
                if (col == 0) {
                    x1 = tableBBox.getX();
                } else {
                    x1 = columnXCoords.get(col - 1);
                }
                if (row == 0) {
                    y2 = tableBBox.getMaxY();
                } else {
                    y2 = lineInformation.getLineBBox().get(row - 1).getY();
                }
                if (col == colCount) {
                    x2 = tableBBox.getMaxX();
                } else {
                    x2 = columnXCoords.get(col);
                }
                if (row == rowCount) {
                    y1 = tableBBox.getY();
                } else {
                    y1 = lineInformation.getLineBBox().get(row).getY();
                }
                cellsInLine.add(new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1));
            }
            cellsInLine = new LinkedList<>();
            cells.add(cellsInLine);
        }

        return cells;
    }

}
