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

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;

import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Document;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.textblock.TextBlock;
import com.knecon.fforesight.service.layoutparser.processor.utils.DrawingOptions;
import com.knecon.fforesight.service.layoutparser.server.utils.BuildDocumentTest;
import com.knecon.fforesight.service.layoutparser.server.utils.visualizations.PdfDraw;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DocumentGraphVisualizationTest extends BuildDocumentTest {

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

        String filename = "files/syngenta/CustomerFiles/Documine/Flora/SOLICITA_VICTRATO-GOLD-II_Item 21_Mutacao_Genica.pdf";
        visualizePdf(filename);
    }


    @Test
    @SneakyThrows
    @Disabled
    public void visualizeRotatedTestDocument() {

        String filename = "files/new/RotateTestFile.pdf";
        visualizePdf(filename);
    }


    @Test
    @SneakyThrows
    @Disabled
    public void visualizeCraftedDocument() {

        String filename = "files/syngenta/CustomerFiles/1 Abamectin_prr.pdf";
        visualizePdf(filename);
    }


    @SneakyThrows
    private void visualizePdf(String filename) {

        Document documentGraph = buildGraph(filename);
        TextBlock textBlock = documentGraph.getTextBlock();

        visualizeSemanticNodes(filename, documentGraph, textBlock);
    }


    private static void visualizeSemanticNodes(String filename, Document documentGraph, TextBlock textBlock) throws IOException {

        File tmpFile = new File("/tmp/" + Path.of(filename).getFileName().toString() + "_SEMANTIC_NODES_BBOX.pdf");
        ClassPathResource fileResource = new ClassPathResource(filename);

        try (PDDocument pdDocument = Loader.loadPDF(fileResource.getFile())) {
            log.info("drawing document");
            PdfDraw.drawDocumentGraph(pdDocument, documentGraph);
            PdfDraw.drawTextBlock(pdDocument, textBlock, DrawingOptions.builder().stroke(true).strokeWidth(0.1f).strokeColor(Color.YELLOW).build());
            log.info("saving document");
            pdDocument.save(tmpFile);
            log.info("saved document");
        }
    }

}
