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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
public class OutlineObjectTree {

    private List<OutlineObjectTreeNode> rootNodes = new ArrayList<>();

    private Map<Integer, List<OutlineObject>> outlineObjectsPerPage = new HashMap<>();


    public OutlineObjectTree(List<OutlineObjectTreeNode> rootNodes) {

        this.rootNodes = rootNodes;
        flattenNodesAndGroupByPage(rootNodes);
    }


    private void flattenNodesAndGroupByPage(List<OutlineObjectTreeNode> outlineObjectTreeNodes) {

        for (OutlineObjectTreeNode node : outlineObjectTreeNodes) {
            int pageNumber = node.getOutlineObject().getPageNumber();
            if (!this.outlineObjectsPerPage.containsKey(pageNumber)) {
                outlineObjectsPerPage.put(pageNumber, new ArrayList<>());
            }
            outlineObjectsPerPage.get(pageNumber).add(node.getOutlineObject());

            if (!node.getChildren().isEmpty()) {
                flattenNodesAndGroupByPage(node.getChildren());
            }
        }
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append("OutlineObjectTree(\n");
        for (OutlineObjectTreeNode node : rootNodes) {
            buildString(node, sb, 1);
        }
        sb.append(")");
        return sb.toString();
    }

    private void buildString(OutlineObjectTreeNode node, StringBuilder sb, int depth) {

        for (int i = 0; i < depth; i++) {
            sb.append("  ");
        }
        sb.append(node.getOutlineObject().getTitle()).append("\n");

        for (OutlineObjectTreeNode child : node.getChildren()) {
            buildString(child, sb, depth + 1);
        }
    }

}
