package com.brilliance.mda.runtime.mda.impl;

import com.brilliance.mda.runtime.mda.*;
import com.brilliance.mda.runtime.mda.util.RuleUtils;

import java.util.*;

/**
 * @Description
 * @Author s_guodong
 * @Date 2022/11/11
 */

public class AttributeValue<E> extends SimpleValue<E> implements IAttribute, IAttributeValue<E> {
    protected transient Map<String, Object> attributes = null;

    protected transient List<IRule> checkRules = null;

    protected transient List<IEventRule> eventRules = null;

    public AttributeValue() {
    }

    public AttributeValue(E value) {
        super(value);
    }

    public AttributeValue(E value, Class clazz) {
        super(value, clazz);
    }

    public Object setAttribute(String name, Object attribute) {
        if (attribute == null)
            return (this.attributes == null) ? null : this.attributes.remove(name);
        if (this.attributes == null)
            this.attributes = new HashMap<String, Object>();
        return this.attributes.put(name, attribute);
    }

    public Object getAttribute(String name) {
        if (this.attributes == null)
            return null;
        return this.attributes.get(name);
    }

    public Set getAttributeNameSet() {
        if (this.attributes == null)
            return Collections.EMPTY_SET;
        return this.attributes.keySet();
    }

    public void addCheckRule(IRule rule) {
        if (this.checkRules == null)
            this.checkRules = new ArrayList<IRule>();
        this.checkRules.add(rule);
    }

    public void addEventRule(IEventRule rule) {
        if (this.eventRules == null)
            this.eventRules = new ArrayList<IEventRule>();
        this.eventRules.add(rule);
    }

    public boolean invokeEventRules(IContext ctx, EventType type, Object data, int... orders) {
        return (this.eventRules == null) ? true : RuleUtils.invoke(this.eventRules, ctx, new Event(this, type, data), orders);
    }

    public boolean invokeCheckRules(IContext ctx) {
        return (this.checkRules == null) ? true : RuleUtils.invoke(this.checkRules, ctx, this);
    }
}

