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

import ru.yandex.common.util.collections.Cf;

/**
 * @author avhaliullin
 */
public class MultiprefixTree<T> implements SuggestIndex<T> {
    private final SuggestMetaIndex<T> delegate;
    private final PrefixTreeNode<T> strictPrefix;
    private final PrefixTreeNode<T> nonStrictPrefix;

    public MultiprefixTree(String name) {
        this.strictPrefix = new PrefixTreeNode<>(name + "; strict prefix");
        this.nonStrictPrefix = new PrefixTreeNode<>(name + "; non-strict prefix");
        this.delegate = new SuggestMetaIndex<>(Cf.list(strictPrefix, nonStrictPrefix));
    }

    public void addResult(String text, T result) {
        strictPrefix.addResult(text, result);
        boolean nonLetterPrefix = false;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (Character.isLetter(c)) {
                if (nonLetterPrefix) {
                    nonStrictPrefix.addResult(text.substring(i), result);
                }
                nonLetterPrefix = false;
            } else {
                nonLetterPrefix = true;
            }
        }
    }

    @Override
    public boolean fillResults(String query, SuggestResultBuilder<T> builder) {
        return delegate.fillResults(query, builder);
    }
}
