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

namespace InABox.DynamicGrid
{
    public class EmbeddedListEditorControl : DynamicEditorControl<string, EmbeddedListEditor>
    {
        
        static EmbeddedListEditorControl()
        {
            //DynamicEditorControlFactory.Register<EmbeddedListEditorControl, EmbeddedListEditor>();
        }
        
        private Button Editor;

        private string _data = "";

        public override void Configure()
        {
        }

        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 listtype = typeof(List<>).MakeGenericType(EditorDefinition.DataType);
            var list = Serialization.Deserialize(listtype, _data) ?? (IList)Activator.CreateInstance(listtype)!;
            var gridtype = DynamicGridUtils.FindDynamicGrid(typeof(DynamicItemsListGrid<>), EditorDefinition.DataType);
            
            var grid = (Activator.CreateInstance(gridtype) as IDynamicItemsListGrid)!;
            grid.Items = list as IEnumerable<object>;
            grid.Options
                .BeginUpdate()
                .Add(DynamicGridOption.AddRows)
                .Add(DynamicGridOption.EditRows)
                .Add(DynamicGridOption.DeleteRows)
                .Add(DynamicGridOption.RecordCount);
            if (EditorDefinition.DirectEdit)
                grid.Options.Add(DynamicGridOption.DirectEdit);
            grid.Options.EndUpdate();
            grid.Refresh(true, true);

            EditorDefinition.CreateButtons(grid);
            
            var window = new DynamicContentDialog((FrameworkElement)grid);
            if (window.ShowDialog() == true)
            {
                _data = Serialization.Serialize(grid.Items);
                CheckChanged();
            }

        }

        public override int DesiredHeight()
        {
            return 25;
        }

        public override int DesiredWidth()
        {
            return 100;
        }

        protected override string RetrieveValue()
        {
            return _data;
        }

        protected override void UpdateValue(string value)
        {
            _data = value;
        }

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

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