using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using InABox.Core;

namespace InABox.DynamicGrid
{
    public class MemoEditorControl : DynamicEditorControl<string, MemoEditor>
    {
        
        static MemoEditorControl()
        {
            //DynamicEditorControlFactory.Register<MemoEditorControl, MemoEditor>();
        }
        
        private TextBox Editor;

        private bool IsChanged;

        public override void Configure()
        {
        }

        protected override FrameworkElement CreateEditor()
        {

            if (!EditorDefinition.Height.IsEffectivelyEqual(0.00))
            {
                MinHeight = EditorDefinition.Height;
                MaxHeight = EditorDefinition.Height;
            }
            else
                MinHeight = 50;

            Editor = new TextBox
            {
                VerticalAlignment = VerticalAlignment.Stretch,
                VerticalContentAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                TextWrapping = TextWrapping.Wrap,
                AcceptsReturn = true,
                
            };
            
            Editor.TextChanged += (o, e) =>
            {
                IsChanged = true;
                if (EditorDefinition.ImmediateUpdates)
                    CheckChanged();
            };
        
            Editor.LostFocus += (o, e) =>
            {
                if (IsChanged)
                    CheckChanged();
            };
            return Editor;
        }

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

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

        protected override string RetrieveValue()
        {
            return Editor.Text;
        }

        protected override void UpdateValue(string value)
        {
            if (value != Editor.Text)
                Editor.Text = value;
        }

        public override void SetFocus()
        {
            Editor.Focus();
            Editor.CaretIndex = string.IsNullOrEmpty(Value) ? 0 : Value.Length;
        }

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