package eu.dnetlib.validator2.engine.builtins;

import eu.dnetlib.validator2.engine.Rule;
import eu.dnetlib.validator2.engine.RuleContext;
import eu.dnetlib.validator2.engine.RuleEvaluationException;
import org.slf4j.LoggerFactory;

import java.util.function.Predicate;

public class SimpleRule<T, C extends RuleContext> implements Rule<T> {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SimpleRule.class);

    private final C context;
    private final Predicate<T> predicate;

    public SimpleRule(C context, Predicate<T> predicate) {
        this.context = context;
        this.predicate = predicate;
    }

    @Override
    public C getContext() {
        return context;
    }

    @Override
    public boolean test(T t) throws RuleEvaluationException {
        try {
            logger.debug("Applying {}", context.getIdProperty().getValue());
            return predicate.test(t);
        } catch (Throwable throwable) {
            // Catch all exceptions here to simplify predicate code
            throw new RuleEvaluationException(throwable.getMessage(), throwable);
        }
    }
}
