using System; using System.Collections.Generic; namespace LeanCloud.Storage.Internal { // TODO: (richardross) refactor entire LeanCloud coder interfaces. public class AVObjectCoder { private static readonly AVObjectCoder instance = new AVObjectCoder(); public static AVObjectCoder Instance { get { return instance; } } // Prevent default constructor. private AVObjectCoder() { } public IDictionary Encode(T state, IDictionary operations, AVEncoder encoder) where T : IObjectState { var result = new Dictionary(); foreach (var pair in operations) { // AVRPCSerialize the data var operation = pair.Value; result[pair.Key] = encoder.Encode(operation); } return result; } public IObjectState Decode(IDictionary data, AVDecoder decoder) { IDictionary serverData = new Dictionary(); var mutableData = new Dictionary(data); string objectId = extractFromDictionary(mutableData, "objectId", (obj) => { return obj as string; }); DateTime? createdAt = extractFromDictionary(mutableData, "createdAt", (obj) => { return AVDecoder.ParseDate(obj as string); }); DateTime? updatedAt = extractFromDictionary(mutableData, "updatedAt", (obj) => { return AVDecoder.ParseDate(obj as string); }); if (mutableData.ContainsKey("ACL")) { serverData["ACL"] = extractFromDictionary(mutableData, "ACL", (obj) => { return new AVACL(obj as IDictionary); }); } string className = extractFromDictionary(mutableData, "className", obj => { return obj as string; }); if (createdAt != null && updatedAt == null) { updatedAt = createdAt; } // Bring in the new server data. foreach (var pair in mutableData) { if (pair.Key == "__type" || pair.Key == "className") { continue; } var value = pair.Value; serverData[pair.Key] = decoder.Decode(value); } return new MutableObjectState { ObjectId = objectId, CreatedAt = createdAt, UpdatedAt = updatedAt, ServerData = serverData, ClassName = className }; } private T extractFromDictionary(IDictionary data, string key, Func action) { T result = default(T); if (data.ContainsKey(key)) { result = action(data[key]); data.Remove(key); } return result; } } }