package eu.dnetlib.validator2.engine.builtins;

import eu.dnetlib.validator2.engine.Helper;
import eu.dnetlib.validator2.engine.contexts.RegularExpressionProperty;

import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

class StandardRegularExpressionProperty extends StandardRuleProperty implements RegularExpressionProperty {

    private static final ConcurrentHashMap<String, Pattern> compiledPatterns = new ConcurrentHashMap<>();

    public StandardRegularExpressionProperty(String name) {
        super(name);
    }

    @Override
    public boolean matches(String text) throws IllegalStateException, PatternSyntaxException {
        String expression = getValue();
        if (Helper.isEmpty(expression)) {
            throw new IllegalStateException("Empty regular expression for property " + getName());
        }

        Pattern pattern = compiledPatterns.computeIfAbsent(expression, Pattern::compile);
        return pattern.matcher(text).matches();
    }

}
