package eu.dnetlib.validator2.engine.builtins;

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

import java.util.Map;

public class XMLCardinalityRule extends XMLRule<XMLContextWithCardinality> {

    protected XMLCardinalityRule(XMLContextWithCardinality context) {
        super(context, (NodeList nodes) ->
                context.getNodeListActionProperty().test(nodes, context.cardinalityPredicate()));
    }

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

    public static class Builder extends AbstractRuleBuilder<XMLCardinalityRule, XMLContextWithCardinality> {

        private Builder() {
            super(new StandardXMLContextWithCardinality());
            context.getNodeListActionProperty().setValue("length");
        }

        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 setRange(String greaterThan, String lessThan) throws IllegalArgumentException {
            context.getLowerBoundProperty().setValue(greaterThan);
            context.getUpperBoundProperty().setValue(lessThan);
            return this;
        }

        public Builder setRange(long greaterThan, long lessThan) {
            context.getLowerBoundProperty().setLongValue(greaterThan);
            context.getUpperBoundProperty().setLongValue(lessThan);
            return this;
        }

        public Builder setIsInclusive(boolean isInclusive) {
            context.getIsInclusiveProperty().setTrue(isInclusive);
            return this;
        }

        @Override
        public XMLCardinalityRule build() throws IllegalStateException {
            ensureContextIsValid();
            return new XMLCardinalityRule(context);
        }

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

}
