package com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes;

import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.Map;

import com.knecon.fforesight.service.layoutparser.internal.api.data.redaction.NodeType;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.NodeVisitor;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.textblock.TextBlock;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.textblock.TextBlockCollector;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.FieldDefaults;
import lombok.experimental.SuperBuilder;

@Data
@SuperBuilder
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class TableCell extends AbstractSemanticNode {

    int row;
    int col;
    boolean header;

    Rectangle2D bBox;

    TextBlock leafTextBlock;

    TextBlock textBlock;


    @Override
    public Map<Page, Rectangle2D> getBBox() {

        Map<Page, Rectangle2D> bBoxPerPage = new HashMap<>();
        getPages().forEach(page -> bBoxPerPage.put(page, bBox));
        return bBoxPerPage;
    }


    @Override
    public void accept(NodeVisitor visitor) {

        visitor.visit(this);
    }


    @Override
    public NodeType getType() {

        return NodeType.TABLE_CELL;
    }


    @Override
    public boolean isLeaf() {

        return getDocumentTree().getEntryById(getTreeId()).getChildren().isEmpty();
    }


    @Override
    public TextBlock getTextBlock() {

        if (isLeaf()) {
            return leafTextBlock;
        }

        if (textBlock == null) {
            textBlock = buildTextBlock();
        }
        return textBlock;
    }


    private TextBlock buildTextBlock() {

        return streamAllSubNodes().filter(SemanticNode::isLeaf)
                .map(SemanticNode::getLeafTextBlock)
                .collect(new TextBlockCollector());
    }


    @Override
    public String toString() {

        return getTreeId() + ": " + NodeType.TABLE_CELL + ": " + this.getTextBlock().buildSummary();
    }

}
