package ru.ulstu.core.service;

import org.springframework.stereotype.Service;
import ru.ulstu.core.model.TreeDto;
import ru.ulstu.core.model.TreeEntity;

import java.util.List;
import java.util.function.Predicate;

@Service
public class TreeService<T extends TreeEntity> {
    public TreeDto getTree(String rootName, List<T> rootItems) {
        return addChildNode(new TreeDto(rootName), rootItems, element -> true);
    }

    public TreeDto getTree(String rootName, List<T> rootItems, Predicate<T> filterPredicate) {
        return addChildNode(new TreeDto(rootName), rootItems, filterPredicate);
    }

    private TreeDto addChildNode(TreeDto currentRoot, List<T> children, Predicate<T> filterPredicate) {
        if (children != null) {
            children.stream()
                    .filter(filterPredicate)
                    .forEach(item -> {
                        TreeDto newNode = new TreeDto(item);
                        currentRoot.getChildren().add(addChildNode(newNode, item.getChildren(), filterPredicate));
                    });
        }
        return currentRoot;
    }
}
