using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Shapes;

namespace TwitterClient.AttachedProperties
{
    class ButtonTemplateAttachedProperties
    {
        public static readonly DependencyProperty ButtonContentForegroundProperty = DependencyProperty.RegisterAttached(
            "ButtonContentForeground",
            typeof(Color),
            typeof(ButtonTemplateAttachedProperties),
            new FrameworkPropertyMetadata(Color.FromArgb(255, 0, 0, 0), FrameworkPropertyMetadataOptions.AffectsRender, OnButtonContentForegroundChanged));

        public static void OnButtonContentForegroundChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is Color)
            {
                var brush = new SolidColorBrush(((Color)e.NewValue)) as Brush;
                if (brush != null)
                {
                    SetForegroundColor(o, brush);
                }
            }
        }

        public static void SetButtonContentForeground(DependencyObject de, Color color)
        {
            var brush = new SolidColorBrush(color);
            SetForegroundColor(de, brush);
        }

        public static Color GetButtonTextForeground(DependencyObject de)
        {
            return (Color)de.GetValue(ButtonContentForegroundProperty);
        }

        public static void SetForegroundColor(DependencyObject de, Brush brush)
        {
            if (de == null)
            {
                return;
            }

            if (de is Shape)
            {
                ((Shape)de).Fill = brush;
            }
            var children = VisualTreeHelper.GetChildrenCount(de);
            if (children > 0)
            {
                for (int i = 0; i < children; i++)
                {
                    var child = VisualTreeHelper.GetChild(de, i) as DependencyObject;
                    if (child != null)
                    {
                        SetForegroundColor(child, brush);
                    }
                }
            }
            else if (de is ContentPresenter)
            {
                SetForegroundColor(((ContentPresenter)de).Content as DependencyObject, brush);
            }

        }

    }
}
