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

import java.io.File;
import java.util.List;

import org.springframework.stereotype.Service;

import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Document;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Headline;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Image;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Paragraph;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Table;
import com.knecon.fforesight.service.layoutparser.processor.visualization.LayoutGrid;
import com.knecon.fforesight.service.viewerdoc.service.PDFTronViewerDocumentService;

import io.micrometer.observation.annotation.Observed;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;

@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class LayoutGridService {

    PDFTronViewerDocumentService viewerDocumentService;


    @SneakyThrows
    @Observed(name = "ViewerDocumentService", contextualName = "create-viewer-document")
    public void addLayoutGrid(File originFile, Document document, File destinationFile, boolean layerVisibilityDefaultValue, boolean writeVisualLayoutParsingGrid) {

        LayoutGrid layoutGrid = createLayoutGrid(document);
        layoutGrid.setVisibleByDefault(layerVisibilityDefaultValue);
//        Visualizations visualLayoutGrid = this.addLayoutGrid(document, layerVisibilityDefaultValue, true);
        if (document.getLayoutDebugLayer().isActive()) {
            viewerDocumentService.addLayerGroups(originFile, destinationFile, List.of(layoutGrid, document.getLayoutDebugLayer()));
        } else {
            viewerDocumentService.addLayerGroups(originFile, destinationFile, List.of(layoutGrid));

        }
    }


    private LayoutGrid createLayoutGrid(Document document) {

        LayoutGrid layoutGrid = new LayoutGrid();
        document.streamAllSubNodes()
                .peek(layoutGrid::addTreeId)
                .forEach(semanticNode -> {
                    switch (semanticNode.getType()) {
                        case SECTION, SUPER_SECTION -> layoutGrid.addSection(semanticNode);
                        case HEADLINE -> layoutGrid.addHeadline((Headline) semanticNode);
                        case PARAGRAPH -> layoutGrid.addParagraph((Paragraph) semanticNode);
                        case TABLE -> layoutGrid.addTable((Table) semanticNode);
                        case IMAGE -> layoutGrid.addImage((Image) semanticNode);
                        case HEADER, FOOTER -> layoutGrid.addHeaderOrFooter(semanticNode);
                    }
                });
        return layoutGrid;
    }

}
