package com.sunwin.metro.drools;


import com.sunwin.metro.bean.DroolsRule;
import com.sunwin.metro.bean.RuleBase;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.conf.ClockTypeOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author kane
 * @date 2020/01/29
 */
public class KieSessionHelper {
    private static final Logger logger = LoggerFactory.getLogger(KieSessionHelper.class);

    private final String rulePackage;
    private final KieServices kieServices;

    public KieSessionHelper(final String pkg) {
        rulePackage = pkg;
        kieServices = KieServices.Factory.get();
    }

    public KieBase createKieBase() {
        return kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId()).getKieBase();
    }



    /**
     * 解析规则RuleBase对象  写到xml文件中
     */
    public List<String> compileRules(RuleBase rb) {
        KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
        KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel(rulePackage)
                .setDefault(true)
                .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
                .setEventProcessingMode(EventProcessingOption.STREAM);

        kieBaseModel.newKieSessionModel("ruleKieSession")
                .setDefault(true)
                .setType(KieSessionModel.KieSessionType.STATEFUL)
                .setClockType(ClockTypeOption.get("realtime"));

        KieFileSystem kfs = kieServices.newKieFileSystem();
        kfs.writeKModuleXML(kieModuleModel.toXML());

        for (DroolsRule droolsRule : rb.getDroolsRules()) {
            //写到xml中
            kfs.write("src/main/resources/" + droolsRule.getType() + "/" + droolsRule.getId() + ".drl", droolsRule.getScript());
        }
        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
        Results results = kieBuilder.getResults();
        if (results.hasMessages(Message.Level.ERROR)) {
            for (Message msg : results.getMessages(Message.Level.ERROR)) {
                logger.error("解析异常 :{}", msg.getText());
            }
        }
        //收集不能即系异常规则
        List<String> res = new ArrayList<>();
        if (results.hasMessages(Message.Level.ERROR)) {
            for (Message msg : results.getMessages(Message.Level.ERROR)) {
                logger.error("解析异常 :{}", msg.getText());
                res.add(msg.getText());
            }
        }
        return res;
    }
}

