package eu.dnetlib.data.utility.cleaner;

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

import org.dom4j.Document;
import org.dom4j.Node;
import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.data.utility.cleaner.rmi.CleanerException;

public abstract class XPATHCleaningRule {

	private String xpath;
	private boolean strict = false;

	public List<Map<String, String>> applyXpathRule(Document doc, String context) throws CleanerException {
		List<Map<String, String>> errors = new ArrayList<Map<String,String>>();
		
		String id = doc.valueOf("//*[local-name()='objIdentifier']"); 
			
		for (Object o : doc.selectNodes(xpath)) {
			Node node = (Node) o;
			String newValue = calculateNewValue(((Node) o).getText().trim(), context, id);
			if (strict) {
				Map<String, String> err = verifyValue(newValue, context, id);
				if (err != null) {
					errors.add(err);
				}
			}
			node.setText(newValue);
		}
		
		return errors;
	}

	protected abstract Map<String, String> verifyValue(String value, String context, String id) throws CleanerException;
	protected abstract String calculateNewValue(String oldValue, String context, String id) throws CleanerException;

	public String getXpath() {
		return xpath;
	}
	
	@Required
	public void setXpath(String xpath) {
		this.xpath = xpath;
	}

	public boolean isStrict() {
		return strict;
	}

	public void setStrict(boolean strict) {
		this.strict = strict;
	}

}
