using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

using DevExpress.Xpf.Scheduler.Drawing;
using Color = System.Windows.Media.Color;

namespace BeWo.Scheduler.Converter
{
	public class DynamicForegroundConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null) return new SolidColorBrush(Colors.Black);

			var scb = value as SolidColorBrush;

			if (value.GetType() != typeof (SolidColorBrush))
			{
				if (value is VisualAppointmentViewInfo)
					scb = new SolidColorBrush(((VisualAppointmentViewInfo) value).LabelColor);
			}

			if (scb != null)
			{
				return Brightness(scb.Color) < 130 ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Colors.Black);
			}

			return new SolidColorBrush(Colors.Black);
		}

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

		private static int Brightness(Color c)
		{
			// return Wert < 130 => es handelt sich bei c um eine dunkle Farbe
			return (int) Math.Sqrt(c.R*c.R*.241 + c.G*c.G*.691 + c.B*c.B*.068);
		}
	}
}