package ru.yandex.webmaster3.storage.spam;

import org.apache.commons.lang3.StringUtils;
import ru.yandex.webmaster3.core.data.WebmasterHostId;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @author avhaliullin
 */
public class SpamFilterUtil {
    private static class TrieNode {
        private final Map<Character, TrieNode> children = new HashMap<>();
        private boolean terminal = false;

        void add(String s, int offset) {
            if (offset < s.length()) {
                children.computeIfAbsent(s.charAt(offset), ign -> new TrieNode())
                        .add(s, offset + 1);
            } else {
                terminal = true;
            }
        }

        boolean matchesAnyPrefix(String s, int offset) {
            if (terminal) {
                return true;
            }
            if (offset < s.length()) {
                TrieNode child = children.get(s.charAt(offset));
                return child != null && child.matchesAnyPrefix(s, offset + 1);
            }
            return false;
        }
    }

    public static Predicate<WebmasterHostId> makeIsBannedPredicateForSuffixes(Collection<String> suffixes) {
        TrieNode trie = new TrieNode();
        for (String suffix : suffixes) {
            trie.add(StringUtils.reverse(suffix), 0);
        }
        return hostId -> {
            String reversedHost = StringUtils.reverse(hostId.getPunycodeHostname());
            return trie.matchesAnyPrefix(reversedHost, 0);
        };
    }
}
