using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Xceed.Wpf.Toolkit;

namespace InABox.DynamicGrid
{
    public class ColorEditorControl : DynamicEditorControl<string, InABox.Core.ColorEditor>
    {

        static ColorEditorControl()
        {
            //DynamicEditorControlFactory.Register<ColorEditorControl, InABox.Core.ColorEditor>();
        }
        
        private ColorPicker Editor;

        public override void Configure()
        {
        }

        protected override FrameworkElement CreateEditor()
        {
            var panel = new DockPanel
            {
                LastChildFill = false
            };

            Editor = new ColorPicker
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                VerticalContentAlignment = VerticalAlignment.Center,
                Width = 150
            };
            Editor.SelectedColorChanged += (o, e) => CheckChanged();
            Editor.SetValue(DockPanel.DockProperty, Dock.Left);

            var clearButton = new Button
            {
                Content = "Clear",
                Margin = new Thickness(5, 0, 0, 0),
                Width = 50
            };
            clearButton.Click += ClearButton_Click;
            Editor.SetValue(DockPanel.DockProperty, Dock.Left);

            panel.Children.Add(Editor);
            panel.Children.Add(clearButton);

            return panel;
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            Editor.SelectedColor = null;
        }

        public override int DesiredHeight()
        {
            return 25;
        }

        public override int DesiredWidth()
        {
            return int.MaxValue;
        }

        protected override string RetrieveValue()
        {
            return Editor.SelectedColor.HasValue ? Editor.SelectedColor.Value.ToString() : "";
        }

        protected override void UpdateValue(string value)
        {
            if (!string.IsNullOrWhiteSpace(value))
                Editor.SelectedColor = (Color)ColorConverter.ConvertFromString(value);
            else
                Editor.SelectedColor = null;
        }

        public override void SetFocus()
        {
            Editor.Focus();
        }

        public override void SetColor(Color color)
        {
            Editor.Background = new SolidColorBrush(color);
        }
    }
}