/// <summary>
/// Given a Shape and sample data, build a literal/instantiation for the
/// Shape's type with the sample data.
/// </summary>
/// <param name="shape">The Shape in the model</param>
/// <param name="data">Sample data to populate the literal with</param>
/// <param name="cb">A CodeBuilder instance to write the code to.</param>
public void GetSampleLiteral(Shape shape, JsonData data, CodeBuilder cb)
{
if (shape.IsString && data.IsString)
{
cb.AppendQuote(data.ToString());
}
if (shape.IsBoolean)
{
cb.Append(data.ToString().ToLower());
}
if (shape.IsFloat || shape.IsInt || shape.IsDouble || shape.IsLong)
{
cb.Append(data.ToString());
}
if (shape.IsList && data.IsArray)
{
var itemType = shape.ListShape;
cb.AppendFormat("new List<{0}> ", ShapeType(itemType)).OpenBlock();
for (int i = 0; i < data.Count; i++)
{
GetSampleLiteral(itemType, data[i], cb);
if (i < (data.Count - 1))
{
cb.AppendLine(",");
}
}
cb.CloseBlock();
}
if (shape.IsMap && data.IsObject)
{
var keyType = shape.KeyShape;
var valType = shape.ValueShape;
cb.AppendFormat("new Dictionary<{0}, {1}> ", ShapeType(keyType), ShapeType(valType));
cb.OpenBlock();
foreach (var k in data.PropertyNames)
{
cb.Append("{ ");
GetSampleLiteral(keyType, k, cb);
cb.Append(", ");
GetSampleLiteral(valType, data[k], cb);
cb.Append(" }");
if (k != data.PropertyNames.Last())
{
cb.AppendLine(",");
}
}
cb.CloseBlock();
}
if (shape.IsStructure && data.IsObject)
{
cb.AppendFormat("new {0} ", ShapeType(shape));
if (data.PropertyNames.Count() > 1)
{
cb.OpenBlock();
}
else
{
cb.Append("{ ");
}
foreach (var field in data.PropertyNames)
{
var property = shape.Members.GetMemberByName(field);
if (null == property)
{
continue;
}
cb.AppendFormat("{0} = ", property.PropertyName);
GetSampleLiteral(property, data[field], cb);
if (field != data.PropertyNames.Last())
{
cb.AppendLine(",");
}
}
if (data.PropertyNames.Count() > 1)
{
cb.CloseBlock();
}
else
{
cb.Append(" }");
}
}
}