package eu.dnetlib.functionality.cql;

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

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

public class CQLFieldLister {

	public Set<String> listFields(final CQLNode node) {
		return doFilter(node, new HashSet<String>());
	}

	private Set<String> doFilter(CQLNode node, Set<String> fields) {

		if (node instanceof CQLBooleanNode) {
			return doFilter((CQLBooleanNode) node, fields);
		}

		if (node instanceof CQLTermNode) {
			return doFilter((CQLTermNode) node, fields);
		}

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

		throw new RuntimeException("error choice");
	}

	private Set<String> doFilter(CQLBooleanNode node, Set<String> fields) {

		Set<String> left = doFilter(node.left, fields);
		Set<String> right = doFilter(node.right, fields);

		left.addAll(right);

		return left;
	}

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

		terms.add(node.getIndex());
		return terms;
	}

}
