aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.BL/ObservableEntityDTO.cs
blob: 1c3edac8270a4592eafa6450667aa71c443f2d13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using LiteDB;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.ActionLogs;
using Tango.BL.ValueObjects;
using Tango.Core.ExtensionMethods;

namespace Tango.BL
{
    /// <summary>
    /// Represents an auto generated observable entity transport object mirror.
    /// </summary>
    /// <typeparam name="DTO">The type of to.</typeparam>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="Tango.BL.IObservableEntityDTO" />
    /// <seealso cref="System.IEquatable{T}" />
    /// <seealso cref="Tango.BL.ActionLogs.IActionLogComparable{DTO}" />
    public abstract class ObservableEntityDTO<DTO, T> : IObservableEntityDTO, IEquatable<T>, IActionLogComparable where T : IObservableEntity where DTO : ObservableEntityDTO<DTO, T>
    {
        /// <summary>
        /// Gets or sets the ID of the entity.
        /// </summary>
        public int ID { get; set; }

        /// <summary>
        /// Gets or sets the unique identifier of the entity.
        /// </summary>
        [BsonId]
        public String Guid { get; set; }

        /// <summary>
        /// Gets or sets the last updated date of the entity.
        /// </summary>
        public DateTime LastUpdated { get; set; }

        /// <summary>
        /// Creates an instance of type <see cref="DTO"/> for the specified entity of type <see cref="T"/>.
        /// </summary>
        /// <param name="observable">The observable.</param>
        /// <returns></returns>
        public static DTO FromObservable(T observable)
        {
            return FromObservableInternal<DTO>(observable);
        }

        /// <summary>
        /// Creates an instance of type <see cref="DTOResult"/> for the specified entity of type <see cref="T"/>.
        /// </summary>
        /// <param name="observable">The observable.</param>
        /// <returns></returns>
        public static DTOResult FromObservable<DTOResult>(T observable) where DTOResult : DTO
        {
            return FromObservableInternal<DTOResult>(observable);
        }

        internal static DTOResult FromObservableInternal<DTOResult>(T observable) where DTOResult : DTO
        {
            if (observable == null) return null;

            var dto = Activator.CreateInstance<DTOResult>();

            foreach (var prop in typeof(DTOResult).GetProperties())
            {
                var observableProp = typeof(T).GetProperty(prop.Name);
                if (observableProp != null)
                {
                    if (prop.PropertyType.IsValueTypeOrString() || prop.PropertyType == typeof(byte[]))
                    {
                        prop.SetValue(dto, observableProp.GetValue(observable));
                    }
                    else if (!prop.PropertyType.IsGenericType)
                    {
                        prop.SetValue(dto, prop.PropertyType.GetMethod(nameof(FromObservableInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).MakeGenericMethod(prop.PropertyType).Invoke(null, new object[] { observableProp.GetValue(observable) }));
                    }
                    else
                    {
                        IList collection = Activator.CreateInstance(prop.PropertyType) as IList;
                        IList source = observableProp.GetValue(observable) as IList;

                        foreach (var item in source)
                        {
                            collection.Add(prop.PropertyType.GenericTypeArguments[0].GetMethod(nameof(FromObservableInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).MakeGenericMethod(prop.PropertyType.GenericTypeArguments[0]).Invoke(null, new object[] { item }));
                        }

                        prop.SetValue(dto, collection);
                    }
                }
                else if (prop.GetCustomAttribute<ObservableDTOPropertyAttribute>() != null)
                {
                    var att = prop.GetCustomAttribute<ObservableDTOPropertyAttribute>();

                    try
                    {
                        prop.SetValue(dto, observable.GetPropertyValueByPath(att.MapsTo));
                    }
                    catch
                    {
                        Debug.WriteLine($"Error mapping '{typeof(DTOResult).Name}.{prop.PropertyType}' to '{typeof(T)}.{att.MapsTo}'.");
                    }
                }
            }

            dto.OnFromObservableCompleted(observable);

            return dto;
        }

        /// <summary>
        /// Creates an entity of type <see cref="T"/> from this DTO.
        /// </summary>
        /// <returns></returns>
        public T ToObservable()
        {
            T observable = Activator.CreateInstance<T>();
            MapToObservable(observable);
            return observable;
        }

        /// <summary>
        /// Maps this instance to an instance of <see cref="T"/>.
        /// </summary>
        /// <param name="observable">The observable.</param>
        public virtual void MapToObservable(T observable)
        {
            foreach (var prop in GetType().GetProperties())
            {
                var observableProp = typeof(T).GetProperty(prop.Name);
                if (observableProp != null)
                {
                    if (prop.PropertyType.IsValueTypeOrString() || prop.PropertyType == typeof(byte[]))
                    {
                        observableProp.SetValue(observable, prop.GetValue(this));
                    }
                    else if (!prop.PropertyType.IsGenericType)
                    {
                        var propInstance = prop.GetValue(this);

                        if (propInstance != null)
                        {
                            var observableInstance = observableProp.GetValue(observable);

                            if (observableInstance == null)
                            {
                                observableInstance = Activator.CreateInstance(observableProp.PropertyType);
                                observableProp.SetValue(observable, observableInstance);
                            }

                            var method = prop.PropertyType.GetRuntimeMethod(nameof(MapToObservable), new Type[] { observableProp.PropertyType });
                            method.Invoke(propInstance, new object[] { observableInstance });
                        }
                    }
                    else
                    {
                        IList collection = prop.GetValue(this) as IList;
                        IList observableCollection = observableProp.GetValue(observable) as IList;

                        if (collection != null)
                        {
                            foreach (var item in collection)
                            {
                                bool found = false;

                                foreach (var o in observableCollection)
                                {
                                    var dtoItem = item as IObservableEntityDTO;
                                    var observableItem = o as IObservableEntity;

                                    if (dtoItem.Guid.Equals(observableItem.Guid))
                                    {
                                        var method = dtoItem.GetType().GetRuntimeMethod(nameof(MapToObservable), new Type[] { observableItem.GetType() });
                                        method.Invoke(dtoItem, new object[] { observableItem });
                                        found = true;
                                        break;
                                    }
                                }

                                if (!found)
                                {
                                    var observableItem = Activator.CreateInstance(observableProp.PropertyType.GenericTypeArguments[0]);
                                    var method = item.GetType().GetRuntimeMethod(nameof(MapToObservable), new Type[] { observableItem.GetType() });
                                    method.Invoke(item, new object[] { observableItem });
                                    observableCollection.Add(observableItem);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Returns true if this instance is equal in terms of values (not references) to the specified entity.
        /// </summary>
        /// <param name="observable">The observable.</param>
        /// <returns></returns>
        public bool EqualsToObservable(T observable)
        {
            if (observable == null) return false;

            foreach (var prop in typeof(DTO).GetProperties())
            {
                var observableProp = typeof(T).GetProperty(prop.Name);
                if (observableProp != null)
                {
                    if (prop.PropertyType.IsValueTypeOrString() || prop.PropertyType == typeof(byte[]))
                    {
                        var observableValue = observableProp.GetValue(observable);
                        var dtoValue = prop.GetValue(this);

                        if (dtoValue == null && observableValue != null) return false;
                        if (dtoValue != null && observableValue == null) return false;

                        if (dtoValue != null && observableValue != null)
                        {
                            if (!dtoValue.Equals(observableValue))
                            {
                                return false;
                            }
                        }
                    }
                    else if (!prop.PropertyType.IsGenericType)
                    {
                        var propInstance = prop.GetValue(this);
                        var observableInstance = observableProp.GetValue(observable);
                        if (propInstance == null && observableInstance != null) return false;

                        if (propInstance != null)
                        {
                            var method = prop.PropertyType.GetRuntimeMethod(nameof(EqualsToObservable), new Type[] { observableInstance.GetType() });

                            if (!((bool)method.Invoke(propInstance, new object[] { observableInstance })))
                            {
                                return false;
                            }
                        }
                    }
                    else
                    {
                        IList source = observableProp.GetValue(observable) as IList;
                        IList collection = prop.GetValue(this) as IList;

                        if (collection == null && source != null) return false;
                        if (source == null && collection != null) return false;

                        if (source != null && collection != null)
                        {
                            if (source.Count != collection.Count) return false;

                            for (int i = 0; i < source.Count; i++)
                            {
                                var item = collection[i];
                                var itemSource = source[i];

                                var method = item.GetType().GetRuntimeMethod(nameof(EqualsToObservable), new Type[] { itemSource.GetType() });

                                if (item == null && itemSource != null) return false;

                                if (!((bool)method.Invoke(item, new object[] { itemSource })))
                                {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Returns true if this instance is equal in terms of values (not references) to the specified entity.
        /// </summary>
        /// <param name="observable">The observable.</param>
        /// <returns></returns>
        public bool Equals(T observable)
        {
            return EqualsToObservable(observable);
        }

        /// <summary>
        /// Returns true if the specified property should be ignored during ActionLog comparison.
        /// </summary>
        /// <param name="propName">Name of the property.</param>
        /// <returns></returns>
        bool IActionLogComparable.ShouldActionLogIgnore(string propName)
        {
            return propName == nameof(LastUpdated) || OnShouldActionLogIgnore(propName);
        }

        /// <summary>
        /// override to specified properties to be ignored when doing ActionLog comparison.
        /// </summary>
        /// <param name="propName">Name of the property.</param>
        /// <returns></returns>
        protected virtual bool OnShouldActionLogIgnore(string propName)
        {
            return false;
        }

        /// <summary>
        /// Returns an optional custom name for this instance in the comparison tree.
        /// </summary>
        /// <returns></returns>
        string IActionLogComparable.GetActionLogName()
        {
            return OnGetActionLogName();
        }

        /// <summary>
        /// override to specified a custom name for this instance in the ActionLog comparison tree.
        /// </summary>
        /// <returns></returns>
        protected virtual String OnGetActionLogName()
        {
            return this.GetType().Name;
        }

        /// <summary>
        /// Called when the static method <see cref="FromObservable(T)"/> completes.
        /// </summary>
        /// <param name="observable">The observable.</param>
        protected virtual void OnFromObservableCompleted(T observable)
        {
            //Just for override
        }
    }
}