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

import java.util.List;

import com.iqser.red.service.redaction.v1.server.model.document.TextRange;
import com.iqser.red.service.redaction.v1.server.model.document.nodes.Page;
import com.iqser.red.service.redaction.v1.server.model.document.nodes.SemanticNode;
import com.iqser.red.service.redaction.v1.server.model.document.textblock.AtomicTextBlock;
import com.knecon.fforesight.service.layoutparser.processor.model.text.Word;

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

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

    int stringOffset;
    long textBlockIdx;


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

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


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

        SearchTextWithTextPositionDto searchTextWithTextPositionDto = SearchTextWithTextPositionFactory.buildSearchTextToTextPositionDto(sequences);
        int offset = stringOffset;
        stringOffset += searchTextWithTextPositionDto.getSearchText().length();
        long idx = textBlockIdx;
        textBlockIdx++;
        String searchText = searchTextWithTextPositionDto.getSearchText();
        return AtomicTextBlock.builder()
                .id(idx)
                .parent(parent)
                .searchText(searchText)
                .numberOnPage(numberOnPage)
                .page(page)
                .lineBreaks(searchTextWithTextPositionDto.getLineBreaks())
                .positions(searchTextWithTextPositionDto.getPositions())
                .stringIdxToPositionIdx(searchTextWithTextPositionDto.getStringIdxToPositionIdx())
                .textRange(new TextRange(offset, offset + searchText.length()))
                .boldTextRanges(searchTextWithTextPositionDto.getBoldTextBoundaries())
                .italicTextRanges(searchTextWithTextPositionDto.getItalicTextBoundaries())
                .build();
    }


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

        return emptyTextBlock(parent, context.getAndIncrementTextBlockNumberOnPage(page), page);
    }


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

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

}
