package cn.stylefeng.workflow.rule.sdk;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.workflow.rule.api.RuleEngineApi;
import cn.stylefeng.workflow.rule.api.condition.BaseRule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngineParameters;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class EasyRuleEngine implements RuleEngineApi {

    private static DefaultRulesEngine rulesEngine;

    public EasyRuleEngine() {
        if (ObjectUtil.isEmpty(rulesEngine)) {
            RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(false).skipOnFirstFailedRule(false);
            rulesEngine = new DefaultRulesEngine(parameters);
        }
    }

    @Override
    public <T> T calcResult(List<? extends BaseRule<T>> conditionList, Map<String, Object> params) {

        Facts facts = new Facts();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (ObjectUtil.isEmpty(entry.getValue())) {
                continue;
            }
            facts.put(entry.getKey(), entry.getValue());
        }

        Rules rules = new Rules();
        for (Object rule : conditionList) {
            rules.register(rule);
        }
        rulesEngine.fire(rules, facts);

        for (BaseRule<T> booleanBaseRuleCondition : conditionList) {
            T result = booleanBaseRuleCondition.getResult();
            if (result != null) {
                return result;
            }
        }

        return null;
    }

}
