package eu.dnetlib.functionality.index.query;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.z3950.zing.cql.CQLBooleanNode;
import org.z3950.zing.cql.CQLNode;
import org.z3950.zing.cql.CQLParseException;
import org.z3950.zing.cql.CQLParser;
import org.z3950.zing.cql.CQLPrefixNode;
import org.z3950.zing.cql.CQLSortNode;
import org.z3950.zing.cql.CQLTermNode;

import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import eu.dnetlib.miscutils.collections.MappedCollection;
import eu.dnetlib.miscutils.functional.UnaryFunction;

/**
 * Use this class to cleanup a CQL tree and obtain all the options
 * 
 * @author marko & claudio
 * 
 */
public class Pruner {
	private static final Log log = LogFactory.getLog(Pruner.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * All options have to be in this namespace.
	 */
	public static final String DNET_URI = "NAMESPACE";

	private String optionUri = DNET_URI;

	/**
	 * Helper method, parse a given CQL string.
	 * 
	 * @param cqlQuery
	 * @return
	 * @throws CQLParseException
	 * @throws IOException
	 */
	CQLNode parse(final String cqlQuery) throws CQLParseException, IOException {
		return new CQLParser().parse(cqlQuery);
	}

	class Result {
		private CQLNode node;
		private List<String> options;

		public Result(final CQLNode node, final List<String> options) {
			super();
			this.node = node;
			this.options = options;
		}

		public Result(final CQLNode node, final Iterable<String> concat) {
			this.node = node;
			this.options = Lists.newArrayList(concat);
		}

		public CQLNode getNode() {
			return node;
		}

		public void setNode(final CQLNode node) {
			this.node = node;
		}

		public List<String> getOptions() {
			return options;
		}

		public void setOptions(final List<String> options) {
			this.options = options;
		}

		public Map<String, List<String>> getOptionMap() {
			Map<String, List<String>> res = new HashMap<String, List<String>>();
			for (String opt : options) {
				String[] k = opt.split("=");
				List<String> l = res.get(k[0]);
				if(l == null)
					l = new ArrayList<String>();
				l.add(k[1]);
				res.put(k[0], l);
			}
			return res;
		}
	}

	/**
	 * Remove all options from a given CQL AST and return all the options.
	 * 
	 * The CQL tree is modified.
	 * 
	 * @param root
	 *            cql tree
	 * @return pair containing a new root node and a list of options
	 */
	public Result prune(final CQLNode root) {
		return prune(new HashMap<String, String>(), root);
	}

	/**
	 * Actual recursive implementation, dispatches the implementation to the appropriate overloaded method.
	 * 
	 * @param prefixes
	 * @param root
	 * @return
	 */
	public Result prune(final Map<String, String> prefixes, final CQLNode root) {

		if (root instanceof CQLBooleanNode)
			return prune(prefixes, (CQLBooleanNode) root);

		if (root instanceof CQLPrefixNode)
			return prune(prefixes, (CQLPrefixNode) root);

		if (root instanceof CQLSortNode)
			return prune(prefixes, (CQLSortNode) root);		
		
		return new Result(root, new ArrayList<String>());
	}
	
	/**
	 * If the current node is a cql "sort" node, just return the inner subtree.
	 * 
	 * @param prefixes
	 * @param node
	 * @return
	 */
	public Result prune(final Map<String, String> prefixes, final CQLSortNode node) {	
		Result res = prune(prefixes, node.subtree);
		node.subtree = res.getNode();
		res.setNode(node);
		return res;
	}

	/**
	 * If the current node is a cql "prefix" node, add his namespace declaration to the current list of namespaces and
	 * return the pruned inner subtree.
	 * 
	 * If the prefix node contains only one single option element, we have to return null. (TODO: perhaps there is a
	 * better solution).
	 * 
	 * @param prefixes
	 * @param node
	 * @return
	 */
	public Result prune(final Map<String, String> prefixes, final CQLPrefixNode node) {
		final HashMap<String, String> subPrefixes = Maps.newHashMap(prefixes);
		subPrefixes.put(node.prefix.name, node.prefix.identifier);
		
		if (isOption(subPrefixes, node.subtree))
			return new Result(null, Lists.newArrayList(getOption(node.subtree)));

		boolean pruneThisPrefix = node.prefix.identifier.equals(optionUri);
		if(pruneThisPrefix)
			return prune(subPrefixes, node.subtree);	
		
		Result res = prune(subPrefixes, node.subtree);
		node.subtree = res.getNode();
		res.setNode(node);
		return res;
		
	}

	/**
	 * boolean prunes are handled in the prune(prefix, node, left, right).
	 * 
	 * @param prefixes
	 * @param node
	 * @return
	 */
	public Result prune(final Map<String, String> prefixes, final CQLBooleanNode node) {
		return prune(prefixes, node, node.left, node.right);
	}

	/**
	 * Detects if a left or right side of a boolean node is a option term, and returns the other side (recursively
	 * pruned). It also returns the accumulated options along the way.
	 * 
	 * @param prefixes
	 * @param bool
	 * @param left
	 * @param right
	 * @return
	 */
	public Result prune(final Map<String, String> prefixes, final CQLBooleanNode bool, final CQLNode left, final CQLNode right) {

		if (isOption(prefixes, left) && isOption(prefixes, right)) {
			List<Result> r = Lists.newArrayList(trimOption(prefixes, left, right), trimOption(prefixes, right, left));

			return new Result(null, Iterables.concat(MappedCollection.map(Iterables.filter(r, Predicates.notNull()),
					new UnaryFunction<Iterable<String>, Result>() {
						@Override
						public Iterable<String> evaluate(Result res) {
							return res.getOptions();
						}
					})));
		}

		Result res = anyNotNull(trimOption(prefixes, left, right), trimOption(prefixes, right, left));

		if (res != null)
			return res;

		final Result leftResult = prune(prefixes, left);
		final Result rightResult = prune(prefixes, right);

		bool.left = leftResult.getNode();
		bool.right = rightResult.getNode();
		return new Result(clean(bool), Iterables.concat(leftResult.getOptions(), rightResult.getOptions()));
	}

	public <T> T anyNotNull(T a, T b) {
		if (a != null)
			return a;
		return b;
	}

	/**
	 * Trims an option from a boolean node if one if it's sides is an option term.
	 * 
	 * Intended to be used once for each sides and then swap.
	 * 
	 * @param prefixes
	 * @param a
	 * @param b
	 * @return
	 */
	public Result trimOption(final Map<String, String> prefixes, final CQLNode a, final CQLNode b) {
		log.debug("trim option?" + prefixes + " a " + a.toCQL());
		if (isOption(prefixes, a)) {
			log.debug("IS OPTION...");
			return trimOption(prefixes, prefixFromOption(a), getOption(a), b);
		}
		log.debug("IS NOT OPTION");
		return null;
	}

	/**
	 * prune(prefixes, bool, left, right) uses this helper method to do the dirty job:
	 * 
	 * we have to detect if a term node is a term option node. by checking the namespace uri associated with the term
	 * prefix according the the current namespace prefix scope (held in prefixes, which is passed down recursively by
	 * copy).
	 * 
	 * @param prefixes
	 * @param ns
	 * @param o
	 * @param subtree
	 * @return
	 */
	public Result trimOption(final Map<String, String> prefixes, final String ns, final String o, final CQLNode subtree) {
		log.debug("trimming " + prefixes + " ns " + ns + " o " + o);
		
		final String namespaceUri = prefixes.get(ns);

		if (!optionUri.equals(namespaceUri)) {
			return null;
		}

		final Result res = prune(prefixes, subtree);
		return new Result(res.getNode(), Iterables.concat(Lists.newArrayList(o), res.getOptions()));
	}

	/**
	 * Drop a boolean node (and, or etc) if one of the sides has been dropped.
	 * 
	 * @param bool
	 * @return
	 */
	private CQLNode clean(final CQLBooleanNode bool) {
		if (bool.left == null)
			return bool.right;
		if (bool.right == null)
			return bool.left;
		return bool;
	}

	////////////////// helpers

	public String getOption(final CQLNode node) {
		return indexFromOption(node) + "=" + termFromOption(node);
	}

	private String indexFromOption(final CQLNode node) {
		return ((CQLTermNode) node).getIndex().replaceAll("[a-z]*\\.(.+)", "$1");
	}

	private String termFromOption(final CQLNode node) {
		return ((CQLTermNode) node).getTerm();
	}

	public String prefixFromOption(final String option) {
		return option.replaceAll("([a-z]*)\\..+", "$1");
	}

	public String prefixFromOption(final CQLNode node) {
		if (node instanceof CQLTermNode)
			return prefixFromOption(((CQLTermNode) node).getIndex());

		return null;
	}

	public boolean isOption(final Map<String, String> prefixes, final String option) {
		return prefixes.containsKey(prefixFromOption(option)) && prefixes.get(prefixFromOption(option)).equals(getOptionUri());
	}

	public boolean isOption(final Map<String, String> prefixes, final CQLNode node) {
		if (node instanceof CQLTermNode)
			return isOption(prefixes, ((CQLTermNode) node).getIndex());

		return false;
	}

	public String getOptionUri() {
		return optionUri;
	}

	public void setOptionUri(String optionUri) {
		this.optionUri = optionUri;
	}
}