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

import java.awt.geom.Rectangle2D;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.jupiter.api.Test;

import com.knecon.fforesight.service.layoutparser.processor.model.PageInformation;
import com.knecon.fforesight.service.layoutparser.processor.model.text.TextPositionSequence;
import com.knecon.fforesight.service.layoutparser.processor.services.InvisibleTableDetectionService;
import com.knecon.fforesight.service.layoutparser.processor.services.PageInformationService;
import com.knecon.fforesight.service.layoutparser.processor.services.PageContentExtractor;
import com.knecon.fforesight.service.layoutparser.processor.utils.RectangleTransformations;
import com.knecon.fforesight.service.layoutparser.server.utils.visualizations.PdfDraw;

import lombok.SneakyThrows;

class InvisibleTableDetectionServiceTest {

    @Test
//    @Disabled
    @SneakyThrows
    public void detectInvisibleTableTest() {

        String fileName = "files/basf/CustomerFiles/invisible_tables_test-two-pages_ocred.pdf";
        var tmpFileName = Path.of("/tmp/").resolve(Path.of(fileName).getFileName() + "_TABLE.pdf").toString();
        List<PageInformation> pageContents = PageContentExtractor.getSortedPageContents(fileName).stream().map(PageInformationService::build).collect(Collectors.toList());

        int pageNumber = 1;
        Rectangle2D tableBBox = pageContents.get(0)
                .getPageContents()
                .getSortedTextPositionSequences()
                .subList(45, 152)
                .stream()
                .map(TextPositionSequence::getRectangle)
                .map(RectangleTransformations::toRectangle2D)
                .map(this::mirrorY)
                .collect(RectangleTransformations.collectBBox());

        List<TextPositionSequence> textPositionSequences = pageContents.get(0)
                .getPageContents()
                .getSortedTextPositionSequences()
                .stream()
                .filter(textPositionSequence -> tableBBox.contains(mirrorY(RectangleTransformations.toRectangle2D(textPositionSequence.getRectangle()))))
                .toList();

        var table = InvisibleTableDetectionService.detectTable(textPositionSequences, tableBBox);

        PdfDraw.drawRectanglesPerPage(fileName, List.of(table.stream().flatMap(Collection::stream).toList(), Collections.emptyList()), tmpFileName);
    }


    private Rectangle2D mirrorY(Rectangle2D rectangle2D) {

        if (rectangle2D.getHeight() >= 0) {
            return rectangle2D;
        }
        return new Rectangle2D.Double(rectangle2D.getX(), rectangle2D.getY() + rectangle2D.getHeight(), rectangle2D.getWidth(), -rectangle2D.getHeight());
    }

}