package ru.yandex.webmaster3.viewer.util.suggest;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * @author avhaliullin
 */
public class PrefixTreeNode<T> implements SuggestIndex<T> {
    private final String indexName;
    private final NavigableMap<Character, PrefixTreeNode<T>> children = new TreeMap<>();
    private final List<T> results = new ArrayList<>();

    public PrefixTreeNode(String indexName) {
        this.indexName = indexName;
    }

    public boolean fillResults(String query, SuggestResultBuilder<T> builder) {
        if (builder.isComplete()) {
            return true;
        }
        if (query.isEmpty()) {
            builder.addAll(indexName, results, false);
            if (builder.isComplete()) {
                return true;
            }

            for (PrefixTreeNode<T> child : children.values()) {
                if (child.fillResults(query, builder)) {
                    return true;
                }
            }
            return false;
        } else {
            PrefixTreeNode<T> child = children.get(query.charAt(0));
            return child != null && child.fillResults(query.substring(1), builder);
        }
    }

    public void addResult(String suffix, T result) {
        if (suffix.isEmpty()) {
            results.add(result);
        } else {
            char c = suffix.charAt(0);
            children.computeIfAbsent(c, x -> new PrefixTreeNode<T>(indexName)).addResult(suffix.substring(1), result);
        }
    }
}
