using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using InABox.Core;
using Syncfusion.Windows.Data;

namespace InABox.DynamicGrid;


public class ListEditorControl : DynamicEditorControl<IList, ListEditor>
{
    static ListEditorControl()
    {
        //DynamicEditorControlFactory.Register<ButtonEditorControl, ButtonEditor>();

    }

    public ListEditorControl()
    {
    }
    
    private Button Editor;

    private IList? _data;

    public int ListWidth { get; set; }
    
    public int ListHeight { get; set; }
    
    public bool DirectEdit { get; set; }
        
    protected override FrameworkElement CreateEditor()
    {
        Editor = new Button
        {
            Content = EditorDefinition.Label,
            HorizontalAlignment = HorizontalAlignment.Stretch,
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
        };
        
        Editor.Click += (sender, args) =>
        {
            if (_data == null)
                return;
            var type = _data.GetType().GetGenericArguments().First();
            var gridtype = DynamicGridUtils.FindDynamicGrid(typeof(DynamicItemsListGrid<>), type);
            var grid = Activator.CreateInstance(gridtype);
            if (grid is not IDynamicItemsListGrid idg )
                return;
            idg.Items = _data;
            idg.OnReconfigure += options =>
            {
                options.AddRows = true;
                options.EditRows = true;
                options.DeleteRows = true;
                options.RecordCount = true;
                if (DirectEdit)
                    options.DirectEdit = true;
            };
            idg.Reconfigure();
            var window = DynamicGridUtils.CreateGridWindow("Edit Items", idg);
            if (ListWidth > 0)
                window.Width = ListWidth;
            if (ListHeight > 0)
                window.Height = ListHeight;
            window.ShowDialog();
        };

        return Editor;
    }

    public override void Configure()
    {
        if (EditorDefinition is not ListEditor editor) 
            return;
        ListWidth = editor.ListWidth;
        ListHeight = editor.ListHeight;
        DirectEdit = editor.DirectEdit;
    }
    
    public override int DesiredHeight()
    {
        return 25;
    }

    public override int DesiredWidth()
    {
        return 100;
    }

    protected override IList RetrieveValue()
    {
        return _data;
    }

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

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

    public override void SetColor(Color color)
    {
    }
}