using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Windows.Data;

namespace MECF.Framework.UI.Core.Converters;

public class EnumDisplayConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var myEnum = (Enum)value;  
        if (myEnum == null)  
        {  
            return null;  
        }  
        var description = GetEnumDisplay(myEnum);
        return !string.IsNullOrEmpty(description) ? description : myEnum.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Empty;
    }

    private string GetEnumDisplay(Enum enumObj)
    {
        if (enumObj == null)
        {
            return string.Empty;
        }

        var fieldInfo = enumObj.GetType().GetField(enumObj.ToString());

        var attribArray = fieldInfo.GetCustomAttributes(false);

        if (attribArray.Length == 0)
        {
            return enumObj.ToString();
        }

        var attrib = attribArray[0] as DisplayAttribute;
        return attrib?.Name;
    }
}