package eu.dnetlib.data.utility.cleaner;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.miscutils.functional.UnaryFunction;

public class CleaningRule implements UnaryFunction<String, String> {

	private static final Log log = LogFactory.getLog(CleaningRule.class); // NOPMD by marko on 11/24/08 5:02 PM

	private List<XPATHCleaningRule> xpathRules = new ArrayList<XPATHCleaningRule>();

	@Override
	public String evaluate(final String text) {

		try {
			final List<Map<String, String>> errors = new ArrayList<Map<String, String>>();
			final Document doc = (new SAXReader()).read(new StringReader(text));
			for (final XPATHCleaningRule r : xpathRules) {
				errors.addAll(r.applyXpathRule(doc));
			}
			if (errors.size() > 0) {
				markAsInvalid(doc, errors);
			}
			return doc.asXML();
		} catch (final Exception e) {
			log.error("Error evaluating rule", e);
		}
		return "";
	}

	private void markAsInvalid(final Document doc, final List<Map<String, String>> errors) {
		final Element element = (Element) doc.selectSingleNode("//*[local-name()='header']");
		if (element != null) {
			final Element inv = element.addElement(new QName("invalid", new Namespace("dri", "http://www.driver-repository.eu/namespace/dri")));
			for (final Map<String, String> e : errors) {
				final Element err = inv.addElement(new QName("error", new Namespace("dri", "http://www.driver-repository.eu/namespace/dri")));
				for (final Map.Entry<String, String> entry : e.entrySet()) {
					err.addAttribute(entry.getKey(), entry.getValue());
				}
			}
			inv.addAttribute("value", "true");
		}
	}

	public List<XPATHCleaningRule> getXpathRules() {
		return xpathRules;
	}

	@Required
	public void setXpathRules(final List<XPATHCleaningRule> xpathRules) {
		this.xpathRules = xpathRules;
	}

}
