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

using BS.Shared;

namespace BeWo.Converter
{
	public class GetEnumDescriptionConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null) return "NULL";

			if (value is Darreichungsform || value is DepotRhythmus)
			{
				var name = value.ToString();
				var fieldNames = value.GetType().GetField(name);
				var attrs = fieldNames.GetCustomAttributes(typeof (DescriptionAttribute), false);
				return (attrs.Length > 0) ? ((DescriptionAttribute) attrs[0]).Description : name;
			}

			string[] str;

			if(parameter.ToString().Equals("DarreichungsformArray"))
			{
				var arr = (Darreichungsform[]) value;
				str = new string[arr.Length];
				for(var i = 0; i < arr.Length; i++)
				{
					var name = arr[i].ToString();
					var fieldNames = arr[i].GetType().GetField(name);
					var attrs = fieldNames.GetCustomAttributes(typeof(DescriptionAttribute), false);
					str[i] = (attrs.Length > 0) ? ((DescriptionAttribute)attrs[0]).Description : name;
				}

				return str;
			}

			var arr2 = (DepotRhythmus[])value;
			str = new string[arr2.Length];
			for (var i = 0; i < arr2.Length; i++)
			{
				var name = arr2[i].ToString();
				var fieldNames = arr2[i].GetType().GetField(name);
				var attrs = fieldNames.GetCustomAttributes(typeof(DescriptionAttribute), false);
				str[i] = (attrs.Length > 0) ? ((DescriptionAttribute)attrs[0]).Description : name;
			}

			return str;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
