using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using TeamAAS.Communication.LightSources; namespace Plugins.Standard.Core { public class LightModelConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { var values = new List(); foreach (LightModel model in Enum.GetValues(typeof(LightModel))) { var field = typeof(LightModel).GetField(model.ToString()); var attr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false) .OfType() .FirstOrDefault(); values.Add(attr?.Description ?? model.ToString()); } return new StandardValuesCollection(values); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || sourceType == typeof(LightModel); public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is LightModel lm) return lm; if (value is string str) { foreach (LightModel model in Enum.GetValues(typeof(LightModel))) { var field = typeof(LightModel).GetField(model.ToString()); var attr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false) .OfType() .FirstOrDefault(); if (attr?.Description == str || model.ToString() == str) return model; } } return LightModel.KCS_KDC_12V60W_4T; } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => destinationType == typeof(string) || destinationType == typeof(LightModel); public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(LightModel) && value is string str) return ConvertFrom(context, culture, str); if (destinationType == typeof(string) && value is LightModel model) { var field = typeof(LightModel).GetField(model.ToString()); var attr = field?.GetCustomAttributes(typeof(DescriptionAttribute), false) .OfType() .FirstOrDefault(); return attr?.Description ?? model.ToString(); } return value; } } }