package eu.dnetlib.data.utility.cleaner;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
//import org.perf4j.StopWatch;
//import org.perf4j.commonslog.CommonsLogStopWatch;
import org.springframework.beans.factory.annotation.Required;

public class XMLCleaningRule implements CleaningRule {

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

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

	public String evaluate(String text, String context) {

		try {

//			StopWatch readerStopWatch = new CommonsLogStopWatch(log);
			SAXReader reader = new SAXReader();
//			readerStopWatch.stop("sax.reader.creation");

//			StopWatch stopWatch = new CommonsLogStopWatch(log);
			Document doc = reader.read(new StringReader(text));
//			stopWatch.stop("parsing.document");

			for (XPATHCleaningRule r : xpathRules) {
//				StopWatch cleaningStopWatch = new CommonsLogStopWatch(log);
				r.applyXpathRule(doc, context);
//				cleaningStopWatch.stop("cleaning.rule");
			}

//			StopWatch serializeStopWatch = new CommonsLogStopWatch(log);
			final String asXML = doc.asXML();
//			serializeStopWatch.stop("serialize");
			return asXML;
		} catch (Exception e) {
			log.error("Error evaluating rule", e);
		}
		return "";

	}

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

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

}
