package eu.dnetlib.validator2.engine.builtins;

import eu.dnetlib.validator2.engine.Helper;
import eu.dnetlib.validator2.engine.contexts.XMLContext;
import org.w3c.dom.NodeList;

import java.util.Map;

public class XMLFieldExistsRule extends XMLRule<XMLContext> {

    protected XMLFieldExistsRule(XMLContext context) {
        super(context, (NodeList nodes) -> {
            /*
            TODO
             - if (nodes.getLength() == 0) return false;
             - Is in original implementation, but results in incorrect evaluation if traversal=0
            */
            return context.getNodeListActionProperty().test(nodes, (String v) -> !Helper.isEmpty(v));
        });
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder extends AbstractRuleBuilder<XMLFieldExistsRule, XMLContext> {

        private Builder() {
            super(new StandardXMLContext()); //the actual implementation is known by the builder only
        }

        public Builder setId(String id) throws IllegalArgumentException {
            context.getIdProperty().setValue(id);
            return this;
        }

        public Builder setXPathExpression(String xpath) throws IllegalArgumentException {
            context.getXPathExpressionProperty().setValue(xpath);
            return this;
        }

        public Builder setNodeListAction(String nodeListAction) throws RuntimeException {
            context.getNodeListActionProperty().setValue(nodeListAction);
            return this;
        }

        @Override
        public XMLFieldExistsRule build() {
            ensureContextIsValid();
            return new XMLFieldExistsRule(context);
        }

        @Override
        public XMLFieldExistsRule buildFrom(Map<String, String> map) {
            context.readFrom(map);
            ensureContextIsValid();
            return new XMLFieldExistsRule(context);
        }
    }

}
