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

import static com.knecon.fforesight.service.layoutparser.processor.model.text.RedTextPosition.HEIGHT_PADDING;

import java.awt.geom.Rectangle2D;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import com.knecon.fforesight.service.layoutparser.processor.model.graph.TextRange;
import com.knecon.fforesight.service.layoutparser.processor.model.text.RedTextPosition;
import com.knecon.fforesight.service.layoutparser.processor.model.text.Word;

import lombok.experimental.UtilityClass;

@UtilityClass
public class SearchTextWithTextPositionFactory {

    // when checking for a hyphen linebreak, we need to check after a linebreak if the last hyphen was less than three symbols away.
    // We detect a linebreak as either a "\n" character or if two adjacent symbol's position differ in y-coordinates by at least one character height.
    // If there is a hyphen linebreak, the hyphen will be 1 position in front of a "\n" or 2 positions in front of the character which has a lower y-coordinate
    // This is why, we need to initialize this to < -2, otherwise, if the very first symbol is a \n we would detect a hyphen linebreak that isn't there.
    // Also, Integer.MIN_VALUE is a bad idea due to potential overflow during arithmetic operations. This is why the default should be -3.
    public final int MAX_HYPHEN_LINEBREAK_DISTANCE = 3;
    public static final double LINEBREAK_DELTA_TOLERANCE = 1.5;


    public SearchTextWithTextPositionDto buildSearchTextToTextPositionDto(List<Word> sequences) {

        if (sequences.isEmpty() || sequences.stream()
                .allMatch(sequence -> sequence.getTextPositions().isEmpty())) {
            return SearchTextWithTextPositionDto.empty();
        }

        Context context = new Context();

        RedTextPosition currentTextPosition = sequences.get(0).getTextPositions().get(0);
        RedTextPosition previousTextPosition = RedTextPosition.builder().unicode(" ").bBoxDirAdj(currentTextPosition.getBBoxDirAdj()).build();

        for (Word word : sequences) {
            for (int i = 0; i < word.getTextPositions().size(); ++i) {

                currentTextPosition = word.getTextPositions().get(i);
                if (isLineBreak(currentTextPosition, previousTextPosition)) {
                    removeHyphenLinebreaks(context);
                    context.lineBreaksStringIdx.add(context.stringIdx);
                }
                if (!isRepeatedWhitespace(currentTextPosition.getUnicode(), previousTextPosition.getUnicode())) {
                    if (isHyphen(currentTextPosition.getUnicode())) {
                        context.lastHyphenIdx = context.stringIdx;
                    }
                    appendCurrentTextPosition(context, currentTextPosition);
                }

                previousTextPosition = currentTextPosition;
                ++context.positionIdx;
            }

            previousTextPosition = RedTextPosition.builder().unicode(" ").bBoxDirAdj(previousTextPosition.getBBoxDirAdj()).build();
            context.stringBuilder.append(" ");
            context.stringIdxToPositionIdx.add(context.positionIdx);
            ++context.stringIdx;
        }

        List<Rectangle2D> positions = sequences.stream()
                .map(Word::getTextPositions)
                .flatMap(Collection::stream)
                .map(RedTextPosition::getBBoxPdf)
                .toList();

        assert context.stringBuilder.length() == context.stringIdxToPositionIdx.size();

        return SearchTextWithTextPositionDto.builder()
                .searchText(context.stringBuilder.toString())
                .lineBreaks(context.lineBreaksStringIdx)
                .stringIdxToPositionIdx(context.stringIdxToPositionIdx)
                .positions(positions)
                .boldTextBoundaries(mergeToBoundaries(context.boldTextsStringIdx))
                .italicTextBoundaries(mergeToBoundaries(context.italicTextStringIdx))
                .build();
    }


    private void appendCurrentTextPosition(Context context, RedTextPosition currentTextPosition) {

        context.stringBuilder.append(currentTextPosition.getUnicode());

        // unicode characters with more than 16-bit encoding have a length > 1 in java strings
        for (int j = 0; j < currentTextPosition.getUnicode().length(); j++) {
            context.stringIdxToPositionIdx.add(context.positionIdx);
            addTextPositionWithFontType(currentTextPosition, "bold", context.boldTextsStringIdx, context.stringIdx);
            addTextPositionWithFontType(currentTextPosition, "italic", context.italicTextStringIdx, context.stringIdx);
        }
        context.stringIdx += currentTextPosition.getUnicode().length();
    }


    private void removeHyphenLinebreaks(Context context) {

        if (lastHyphenDirectlyBeforeLineBreak(context)) {
            context.stringBuilder.delete(context.lastHyphenIdx, context.stringBuilder.length());
            context.stringIdxToPositionIdx = context.stringIdxToPositionIdx.subList(0, context.lastHyphenIdx);
            context.stringIdx = context.lastHyphenIdx;
            context.lastHyphenIdx = -MAX_HYPHEN_LINEBREAK_DISTANCE;
        }
    }


    private boolean lastHyphenDirectlyBeforeLineBreak(Context context) {

        return context.stringIdx - context.lastHyphenIdx < MAX_HYPHEN_LINEBREAK_DISTANCE;
    }


    private static List<TextRange> mergeToBoundaries(List<Integer> integers) {

        if (integers.isEmpty()) {
            return Collections.emptyList();
        }
        List<TextRange> boundaries = new LinkedList<>();
        int start = integers.get(0);
        int end = integers.get(0) + 1;
        for (int current : integers) {
            if (current > end + 1) {
                boundaries.add(new TextRange(start, end));
                start = current;
            }
            end = current + 1;
        }
        if (boundaries.isEmpty()) {
            boundaries.add(new TextRange(start, end));
        }
        return boundaries;
    }


    private static void addTextPositionWithFontType(RedTextPosition currentTextPosition, String fontType, List<Integer> fontTypePositions, int stringIdx) {

        if (currentTextPosition.getFontName() != null && currentTextPosition.getFontName().toLowerCase(Locale.ROOT).contains(fontType)) {
            fontTypePositions.add(stringIdx);
        }
    }


    private boolean isLineBreak(RedTextPosition currentTextPosition, RedTextPosition previousTextPosition) {

        return Objects.equals(currentTextPosition.getUnicode(), "\n") || isDeltaYLargerThanTextHeight(currentTextPosition, previousTextPosition);
    }


    private boolean isDeltaYLargerThanTextHeight(RedTextPosition currentPosition, RedTextPosition previousPosition) {

        if (previousPosition == null) {
            return false;
        }

        double deltaY = (Math.abs(currentPosition.getYDirAdj() - previousPosition.getYDirAdj()) * LINEBREAK_DELTA_TOLERANCE) + (2 * HEIGHT_PADDING);
        return deltaY >= currentPosition.getHeightDirAdj() || deltaY >= previousPosition.getHeightDirAdj();
    }


    private boolean isRepeatedWhitespace(String currentUnicode, String previousUnicode) {

        return Objects.equals(previousUnicode, " ") && Objects.equals(currentUnicode, " ");
    }


    private boolean isHyphen(String unicodeCharacter) {

        return Objects.equals(unicodeCharacter, "-") || //
               Objects.equals(unicodeCharacter, "~") || //
               Objects.equals(unicodeCharacter, "‐") || //
               Objects.equals(unicodeCharacter, "‒") || //
               Objects.equals(unicodeCharacter, "⁻") || //
               Objects.equals(unicodeCharacter, "−") || //
               Objects.equals(unicodeCharacter, "﹣") || //
               Objects.equals(unicodeCharacter, "゠") || //
               Objects.equals(unicodeCharacter, "⁓") || //
               Objects.equals(unicodeCharacter, "‑") || //
               Objects.equals(unicodeCharacter, "\u00AD");
    }


    private class Context {

        List<Integer> stringIdxToPositionIdx = new LinkedList<>();
        List<Integer> lineBreaksStringIdx = new LinkedList<>();
        List<Integer> boldTextsStringIdx = new LinkedList<>();
        List<Integer> italicTextStringIdx = new LinkedList<>();
        StringBuilder stringBuilder = new StringBuilder();

        int stringIdx;
        int positionIdx;

        int lastHyphenIdx = -MAX_HYPHEN_LINEBREAK_DISTANCE;

    }

}
