@Override
public LocalPage getClosestCategory(LocalPage page, Set<LocalPage> candidates, boolean weightedDistance) throws DaoException {
CategoryGraph graph = getGraph(page.getLanguage());
CategoryBfs bfs = new CategoryBfs(graph, page.getLocalId(), page.getLanguage(), Integer.MAX_VALUE, null, this);
bfs.setAddPages(false);
bfs.setExploreChildren(false);
Map<Integer, LocalPage> indexToCandidates = new HashMap<Integer, LocalPage>();
for (LocalPage c : candidates) {
indexToCandidates.put(graph.catIdToIndex(c.getLocalId()), c);
}
List<LocalPage> matches = new ArrayList<LocalPage>();
while (bfs.hasMoreResults() && matches.isEmpty()) {
CategoryBfs.BfsVisited visited = bfs.step();
for (int catId : visited.cats.keys()) {
if (indexToCandidates.containsKey(catId)) {
matches.add(indexToCandidates.get(catId));
}
}
}
if (matches.isEmpty()) {
return null;
} else {
return matches.get(new Random().nextInt(matches.size()));
}
}