package eu.dnetlib.validator2.engine.builtins;

import eu.dnetlib.validator2.engine.contexts.RegularExpressionProperty;
import eu.dnetlib.validator2.engine.contexts.XMLContextWithRegularExpression;
import org.w3c.dom.NodeList;

import java.util.Map;
import java.util.function.Predicate;

public class XMLRegularExpressionRule extends XMLRule<XMLContextWithRegularExpression> {

    protected XMLRegularExpressionRule(XMLContextWithRegularExpression context) {
        super(context, (NodeList nodes) -> {
            RegularExpressionProperty regex = context.getRegularExpressionProperty();
            return context.getNodeListActionProperty().test(nodes, (Predicate<String>) regex::matches);
        });
    }

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

    public static class Builder extends AbstractRuleBuilder<XMLRegularExpressionRule, XMLContextWithRegularExpression> {

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

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

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

        public Builder setRegularExpression(String regexp) {
            context.getRegularExpressionProperty().setValue(regexp);
            return this;
        }

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

        public XMLRegularExpressionRule build() {
            ensureContextIsValid();
            return new XMLRegularExpressionRule(context);
        }

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


}
