package com.sunwin.metro.bean;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunwin.metro.utils.Md5Util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 规则集合  可以包括多个规则
 *
 * @author sunwin
 */
public class RuleBase implements Serializable {
    private static final long serialVersionUID = -6249685986229931397L;
    private List<DroolsRule> droolsRules = new ArrayList<>();
    private String name = "Empty-Name";
    private String hash = "";

    public static RuleBase createRuleBase(JSONArray jsonArray) {
        RuleBase ruleBase = new RuleBase();
        for (Object obj : jsonArray) {
            //JSONObject job = (JSONObject) obj;
            JSONObject job = JSONObject.parseObject(JSONObject.toJSONString(obj));
            DroolsRule droolsRule = new DroolsRule();
            droolsRule.setId(job.getString("id"));
            droolsRule.setType(job.getString("type"));
            droolsRule.setScript(job.getString("script"));
            droolsRule.setState(job.getString("state"));
            ruleBase.droolsRules.add(droolsRule);
        }
        String str = ruleBase.toString();
        //给字符串取md5
        ruleBase.hash = Md5Util.getMd5(str);
        ruleBase.name = "rules-" + ruleBase.hash;
        return ruleBase;
    }

    public static RuleBase createRuleBase(JSONArray jsonArray, String name) {
        RuleBase ruleBase = createRuleBase(jsonArray);
        ruleBase.name = name;
        return ruleBase;
    }

    public List<DroolsRule> getDroolsRules() {
        return droolsRules;
    }

    public void setDroolsRules(List<DroolsRule> droolsRules) {
        this.droolsRules = droolsRules;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    @Override
    public String toString() {
        return "RuleBase{" +
                "rules=" + droolsRules +
                ", name='" + name + '\'' +
                ", hash='" + hash + '\'' +
                '}';
    }
}
