package de.zalando.toga.generator.dimensions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.TextNode;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
public abstract class Dimension {
private enum Type {
OBJECT,
STRING,
ENUM
}
protected final String name;
protected final List<String> values = new ArrayList<>();
public Dimension(String name) {
this.name = name;
}
public static Dimension from(String name, JsonNode node) {
Type type = deriveType(node);
switch (type) {
case OBJECT:
return new ObjectDimension(name, node);
case STRING:
return new StringDimension(name, node);
case ENUM:
return new EnumDimension(name, node);
default:
throw new IllegalArgumentException("JSON attribute with type [" + type + "] is not supported.");
}
}
private static Type deriveType(JsonNode node) {
JsonNode typeNode = node.path("type");
if (typeNode.isMissingNode() || !typeNode.isValueNode()) {
JsonNode enumNode = node.path("enum");
if (!enumNode.isMissingNode() && enumNode.isArray()) {
return Type.ENUM;
}
throw new IllegalArgumentException("Could not derive type from node [" + node.toString() + "].");
}
return Type.valueOf(typeNode.asText().toUpperCase());
}
public String getFieldName() {
return name;
}
/**
* Generate a list of JSON representations of the dimension.
* This generated JSON is intended to be combined into JSON objects right away without further modification.
*
* @return a list of json representations with all the different options the dimension contains.
*/
public List<JsonNode> getValueDimensions() {
return values.stream().map(TextNode::valueOf).collect(toList());
};
}