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;
import java.util.function.Predicate;

public class XMLValidURLRule extends XMLRule<XMLContext> {

    protected XMLValidURLRule(XMLContext context) {
        super(context, (NodeList nodes) -> context.getNodeListActionProperty().test(nodes, (Predicate<String>) Helper.URLResolver::resolve));
    }

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

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

        private Builder() {
            super(new StandardXMLContext());
        }

        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 XMLValidURLRule build() {
            ensureContextIsValid();
            return new XMLValidURLRule(context);
        }

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

    }

}
