package eu.dnetlib.functionality.index.query;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.z3950.zing.cql.*;

/**
 * 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 the parsed CQLNode
	 * @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 the pruned result
	 */
	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 the pruned result
	 */
	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 the pruned result
	 */
	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 the pruned result
	 */
	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 the pruned result
	 */
	public Result prune(final Map<String, String> prefixes, final CQLBooleanNode bool, final CQLNode left, final CQLNode right) {

		if (isOption(prefixes, left) && isOption(prefixes, right)) {
			return new Result(null, Stream.of(trimOption(prefixes, left, right), trimOption(prefixes, right, left))
					.filter(Objects::nonNull)
					.map(i -> i.getOptions())
					.map(i -> i.stream())
					.flatMap(i -> i)
					.collect(Collectors.toList()));
		}

		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 the pruned result
	 */
	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 the pruned result
	 */
	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 the pruned result
	 */
	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;
	}
}
