package eu.dnetlib.functionality.cql;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.z3950.zing.cql.CQLBooleanNode;
import org.z3950.zing.cql.CQLNode;
import org.z3950.zing.cql.CQLTermNode;

import com.google.common.collect.Lists;

public class CqlTermLister {

	public List<String> listTerms(final CQLNode node, final String field) {
		return Lists.newArrayList(doListTerms(node, field, new HashSet<String>()));
	}

	private Set<String> doListTerms(CQLNode node, String field, Set<String> terms) {

		if (node instanceof CQLBooleanNode) {
			return doListTerms((CQLBooleanNode) node, field, terms);
		}

		if (node instanceof CQLTermNode) {
			return doListTerms((CQLTermNode) node, field, terms);
		}

		if (node == null) {
			return terms;
		}

		throw new RuntimeException("error choice");
	}

	private Set<String> doListTerms(CQLBooleanNode node, String field, Set<String> terms) {

		Set<String> left = doListTerms(node.left, field, terms);
		Set<String> right = doListTerms(node.right, field, terms);

		left.addAll(right);

		return left;
	}

	private static Set<String> doListTerms(CQLTermNode node, String field, Set<String> terms) {

		if (field.equalsIgnoreCase(node.getIndex())) {
			terms.add(node.getTerm());
		}

		return terms;
	}

}
