using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace WPFCatalog
{
    public class MaddoColorConverter : IValueConverter
    {
        private static readonly DependencyObject _dummy = new DependencyObject();

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Color color = Colors.Black;

            if (value != null && value != DependencyProperty.UnsetValue && value is string && !String.IsNullOrWhiteSpace((string)value))
            {
                string c = (string)value;
                object convertedColor = null;
                try
                {
                    convertedColor = ColorConverter.ConvertFromString(c);
                }
                catch (Exception ex)
                {
                    if (!DesignerProperties.GetIsInDesignMode(_dummy))
                    {
                        throw new FormatException($"String {c} does not represent a valid color", ex);
                    }
                }
                if (convertedColor != null)
                {
                    color = (Color)convertedColor;
                }
            }

            return color;

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                Color color = (Color)value;
                Debug.WriteLine(color.ToString());
                return color.ToString();
            }
            return string.Empty;
        }
    }
}
