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

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.knecon.fforesight.service.layoutparser.processor.model.AbstractPageBlock;
import com.knecon.fforesight.service.layoutparser.processor.model.graph.nodes.GenericSemanticNode;
import com.knecon.fforesight.service.layoutparser.processor.model.image.ClassifiedImage;
import com.knecon.fforesight.service.layoutparser.processor.model.text.TextPageBlock;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class TableOfContentItem {

    @EqualsAndHashCode.Include
    private TextPageBlock headline;
    private List<TableOfContentItem> children = new ArrayList<>();
    private TableOfContentItem parent;

    private List<AbstractPageBlock> sectionBlocks = new ArrayList<>();
    private List<ClassifiedImage> images = new ArrayList<>();

    private GenericSemanticNode section;


    public TableOfContentItem(TextPageBlock headline) {

        this.headline = headline;
    }


    public void addChild(TableOfContentItem tableOfContentItem) {

        children.add(tableOfContentItem);
        tableOfContentItem.setParent(this);
    }


    public TableOfContentItem getSiblingBefore() {

        if (parent != null) {
            int index = parent.getChildren().indexOf(this);
            if (index > 0) {
                return parent.getChildren().get(index - 1);
            }
        }
        return null;
    }


    public TableOfContentItem getSiblingAfter() {

        if (parent != null) {
            int index = parent.getChildren().indexOf(this);
            if (index >= 0 && index < parent.getChildren().size() - 1) {
                return parent.getChildren().get(index + 1);
            }
        }
        return null;
    }


    public boolean contains(TextPageBlock block) {

        if (headline.equals(block)) {
            return true;
        }
        for (TableOfContentItem child : children) {
            if (child.contains(block)) {
                return true;
            }
        }
        return false;
    }


    public boolean contains(TableOfContentItem tocItem) {

        if (this.equals(tocItem)) {
            return true;
        }
        for (TableOfContentItem child : children) {
            if (child.contains(tocItem)) {
                return true;
            }
        }
        return false;
    }


    public List<AbstractPageBlock> getNonEmptySectionBlocks() {

        return sectionBlocks.stream()
                .filter(pageBlock -> !pageBlock.isEmpty())
                .collect(Collectors.toList());
    }


    @Override
    public String toString() {

        return "OutlineObjectTreeNode{" + "textPageBlock=" + headline + '}';
    }

}
