package com.knecon.fforesight.service.layoutparser.processor.model.table;

import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.knecon.fforesight.service.layoutparser.processor.model.text.TextPageBlock;
import com.knecon.fforesight.service.layoutparser.processor.model.text.TextPositionSequence;
import com.knecon.fforesight.service.layoutparser.processor.utils.TextNormalizationUtilities;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@SuppressWarnings("serial")
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class Cell extends Rectangle {

    private List<TextPageBlock> textBlocks = new ArrayList<>();

    private List<Cell> headerCells = new ArrayList<>();

    private boolean isHeaderCell;

    private static final int MIN_SIZE = 1;

    private int pageNumber;


    public Cell(Point2D topLeft, Point2D bottomRight) {

        super((float) topLeft.getY(), (float) topLeft.getX(), (float) (bottomRight.getX() - topLeft.getX()), (float) (bottomRight.getY() - topLeft.getY()));
    }


    public Cell(Rectangle2D r) {

        super((float) r.getY(), (float) r.getX(), (float) r.getWidth(), (float) r.getHeight());
    }


    public void addTextBlock(TextPageBlock textBlock) {

        textBlocks.add(textBlock);
    }


    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();

        Iterator<TextPageBlock> itty = textBlocks.iterator();
        TextPositionSequence previous = null;
        while (itty.hasNext()) {

            TextPageBlock textBlock = itty.next();

            for (TextPositionSequence word : textBlock.getSequences()) {
                if (previous != null) {
                    if (Math.abs(previous.getMaxYDirAdj() - word.getMaxYDirAdj()) > word.getTextHeight()) {
                        sb.append('\n');
                    } else {
                        sb.append(' ');
                    }
                }
                sb.append(word.toString());
                previous = word;
            }

        }

        return TextNormalizationUtilities.removeHyphenLineBreaks(sb.toString()).replaceAll("\n", " ").replaceAll(" {2}", " ");
    }


    public boolean hasMinimumSize() {

        return this.getHeight() >= MIN_SIZE && this.getWidth() >= MIN_SIZE;
    }

}
