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

namespace InABox.DynamicGrid
{
    public class BlobEditorControl : DynamicEditorControl<byte[], BlobEditor>
    {
        
        static BlobEditorControl()
        {
            //DynamicEditorControlFactory.Register<BlobEditorControl, BlobEditor>();
        }
        
        private Button Editor;

        private byte[] _data = new byte[] { };

        public Action<object, BlobEditorClickArgs> OnClick { get; set; }

        public override void Configure()
        {
            if (EditorDefinition is not BlobEditor editor) return;

            OnClick += editor.OnClick;
        }

        protected override FrameworkElement CreateEditor()
        {
            Editor = new Button
            {
                Content = EditorDefinition.Label,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                VerticalContentAlignment = VerticalAlignment.Center,
            };
            Editor.Click += Editor_Click;

            return Editor;
        }

        private void Editor_Click(object sender, RoutedEventArgs e)
        {
            var args = new BlobEditorClickArgs() { Cancel = false, Data = _data };
            OnClick?.Invoke(this, args);
            if (!args.Cancel)
                _data = args.Data;
        }

        public override int DesiredHeight()
        {
            return 25;
        }

        public override int DesiredWidth()
        {
            return 100;
        }

        protected override byte[] RetrieveValue()
        {
            return _data;
        }

        protected override void UpdateValue(byte[] value)
        {
            _data = value;
        }

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

        public override void SetColor(Color color)
        {
        }
    }
}