Newer
Older
AlgebraicDataflowArchitectureModel / AlgebraicDataflowArchitectureModel / src / models / dataConstraintModel / JsonTerm.java
package models.dataConstraintModel;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import models.algebra.Constant;
import models.algebra.Expression;
import models.algebra.Symbol;
import models.algebra.Term;
import parser.Parser;

public class JsonTerm extends Term {
	private Map<String, Integer> keyToIndex = new HashMap<>();

	public JsonTerm() {
		super(new Symbol("json", -1));
		setType(DataConstraintModel.typeJson);
	}
	
	public void addMember(String key, Expression value) {
		if (keyToIndex.containsKey(key)) {
			setChild(keyToIndex.get(key), value);
		} else {
			keyToIndex.put(key, getChildren().size());
			addChild(value);
		}
	}
	
	public Set<String> keySet() {
		return keyToIndex.keySet();
	}

	public Expression get(String key) {
		if (keyToIndex.get(key) == null) return null;
		return getChild(keyToIndex.get(key));
	}

	public Expression get(Constant key) {
		if (keyToIndex.get(key.getValue()) == null) return null;
		return getChild(keyToIndex.get(key.getValue()));
	}
	
	@Override
	public Object clone() {
		JsonTerm newTerm = new JsonTerm();
		for (Expression e: children) {
			newTerm.addChild((Expression) e.clone());
		}
		newTerm.keyToIndex = new HashMap<String, Integer>(keyToIndex);
		return newTerm;
	}
	
	public String toString() {
		String jsonStr = "{";
		String delim = "";
		for (String key: keyToIndex.keySet()) {
			jsonStr += delim + Parser.DOUBLE_QUOT + key + Parser.DOUBLE_QUOT + ": " + getChild(keyToIndex.get(key)).toString();
			delim = ", ";
		}
		return jsonStr + "}";
	}
}