#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ArdupilotMega.Attributes;
#endregion
namespace ArdupilotMega.Utilities
{
public static class EnumTranslator
{
///
/// Translates this instance.
///
///
///
public static Dictionary Translate()
{
return Translate(true);
}
///
/// Translates the specified check private.
///
///
/// if set to true [check private].
///
public static Dictionary Translate(bool checkPrivate)
{
return Translate(string.Empty, checkPrivate);
}
///
/// Translates the specified default text.
///
///
/// The default text.
/// if set to true [check private].
///
public static Dictionary Translate(string defaultText, bool checkPrivate)
{
return Translate(defaultText, checkPrivate, true);
}
///
/// Translates the specified default text.
///
///
/// The default text.
/// if set to true [check private].
/// if set to true [sorting].
///
public static Dictionary Translate(string defaultText, bool checkPrivate, bool sorting)
{
var types = new Dictionary();
var tempTypes = new Dictionary();
if (!String.IsNullOrEmpty(defaultText)) types.Add(-1, defaultText);
foreach (FieldInfo fieldInfo in typeof(T).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
{
bool add = true;
string displayText = string.Empty;
T type = (T)fieldInfo.GetValue(typeof(T));
object[] displayTextObjectArr = fieldInfo.GetCustomAttributes(typeof(DisplayTextAttribute), true);
displayText = (displayTextObjectArr.Length > 0)
? ((DisplayTextAttribute)displayTextObjectArr[0]).Text
: type.ToString();
if (checkPrivate)
{
object[] privateAttributeObjectArr = fieldInfo.GetCustomAttributes(typeof(PrivateAttribute), true);
if (privateAttributeObjectArr.Length > 0)
{
add = !((PrivateAttribute)privateAttributeObjectArr[0]).IsPrivate;
}
}
if (add)
{
tempTypes.Add(Convert.ToInt32(type), displayText);
}
}
if (sorting)
{
foreach(var x in tempTypes.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value)){ types.Add(x.Key, x.Value); }
}
else
{
foreach (var x in tempTypes.ToDictionary(x => x.Key, x => x.Value)) { types.Add(x.Key, x.Value); }
}
return types;
}
///
/// Gets the display text.
///
///
/// The value.
///
public static string GetDisplayText(T value)
{
var displayText = string.Empty;
var fieldInfo = value.GetType().GetField(value.ToString());
if(fieldInfo != null)
{
T type = (T)fieldInfo.GetValue(typeof(T));
if(type != null)
{
object[] displayTextObjectArr = fieldInfo.GetCustomAttributes(typeof(DisplayTextAttribute), true);
displayText = (displayTextObjectArr.Length > 0)
? ((DisplayTextAttribute)displayTextObjectArr[0]).Text
: type.ToString();
}
}
return displayText;
}
}
}