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

import java.util.List;

import com.knecon.fforesight.service.layoutparser.processor.model.text.TextPositionSequence;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.Page;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.SemanticNode;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.textblock.AtomicTextBlock;

import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;

@FieldDefaults(level = AccessLevel.PRIVATE)
public class TextBlockFactory {

    int stringOffset;
    long textBlockIdx;


    public AtomicTextBlock buildAtomicTextBlock(List<TextPositionSequence> sequences, SemanticNode parent, DocumentGraphFactory.Context context, Page page) {

        Integer numberOnPage = context.getAndIncrementTextBlockNumberOnPage(page);
        return buildAtomicTextBlock(sequences, parent, numberOnPage, page);
    }


    public AtomicTextBlock buildAtomicTextBlock(List<TextPositionSequence> sequences, SemanticNode parent, Integer numberOnPage, Page page) {

        SearchTextWithTextPositionDto searchTextWithTextPositionDto = SearchTextWithTextPositionFactory.buildSearchTextToTextPositionDto(sequences);
        int offset = stringOffset;
        stringOffset += searchTextWithTextPositionDto.getSearchText().length();
        long idx = textBlockIdx;
        textBlockIdx++;
        String orientation;
        int textDirection;
        if (sequences.isEmpty()) {
            orientation = null;
            textDirection = 0;
        } else {
            orientation = sequences.get(0).getDir().toString();
            textDirection = sequences.get(0).getRotation();
        }
        return AtomicTextBlock.fromSearchTextWithTextPosition(searchTextWithTextPositionDto.getSearchText(),
                searchTextWithTextPositionDto.getLineBreaks(),
                searchTextWithTextPositionDto.getBoldTextBoundaries(),
                searchTextWithTextPositionDto.getItalicTextBoundaries(),
                searchTextWithTextPositionDto.getPositions(),
                searchTextWithTextPositionDto.getStringIdxToPositionIdx(),
                idx,
                parent,
                numberOnPage,
                page,
                offset,
                orientation,
                textDirection);
    }


    public AtomicTextBlock emptyTextBlock(SemanticNode parent, DocumentGraphFactory.Context context, Page page) {

        long idx = textBlockIdx;
        textBlockIdx++;
        return AtomicTextBlock.empty(idx, stringOffset, page, context.getAndIncrementTextBlockNumberOnPage(page), parent);
    }


    public AtomicTextBlock emptyTextBlock(SemanticNode parent, Integer numberOnPage, Page page) {

        long idx = textBlockIdx;
        textBlockIdx++;
        return AtomicTextBlock.empty(idx, stringOffset, page, numberOnPage, parent);
    }

}
