using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Amazon.CloudSearchDomain.Model; using Hyper.ComponentModel; using Sony.Filtr.Search.SearchItems; namespace Sony.Filtr.Search { public class CloudSearchMapper { public IEnumerable Map(Hits hits) where T : class, new() { return hits.Hit.Select(Map); } public T Map(Hit hit) where T: class, new() { var type = typeof (T); if (hit.Fields["typename"].FirstOrDefault() == type.Name) { T obj = new T(); foreach (var p in GetProperties(type)) { var propertyFieldName = p.Name.ToLower(); List hitFieldValues; if (!hit.Fields.TryGetValue(propertyFieldName, out hitFieldValues)) continue; if (p.PropertyType == typeof(List)) { p.SetValue(obj, hit.Fields[propertyFieldName]); } else if (p.PropertyType == typeof(string)) { p.SetValue(obj, hit.Fields[propertyFieldName].FirstOrDefault()); } else if (p.PropertyType == typeof(int)) { var value = int.Parse(hitFieldValues.First()); p.SetValue(obj, value); } else if (p.PropertyType == typeof(long?)) { long value; if (long.TryParse(hitFieldValues.First(), out value)) p.SetValue(obj, value); } else if (p.PropertyType == typeof(int?)) { int value; if (int.TryParse(hitFieldValues.First(), out value)) p.SetValue(obj, value); } else if (p.PropertyType == typeof(bool)) { var boolString = hitFieldValues.First(); if (boolString == "1") p.SetValue(obj, true); } else if (p.PropertyType == typeof(double)) { var value = double.Parse(hitFieldValues.First()); p.SetValue(obj, value); } else if (p.PropertyType == typeof(double?)) { foreach (var hitFieldValue in hitFieldValues) { double value; if (double.TryParse(hitFieldValue, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value)) { p.SetValue(obj, value); break; } } } else if (p.PropertyType == typeof(float)) { var value = float.Parse(hitFieldValues.First()); p.SetValue(obj, value); } } return obj; } return null; } private static IEnumerable GetProperties(Type type) where T: class, new() { return type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p=> p.CanWrite && p.CanRead); } } }