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 netDxf.Tables;
using Syncfusion.Windows.Shared;

namespace InABox.DynamicGrid;

public class ArrayValueNode<TValueNode> : ValueNode where TValueNode : ValueNode, new() {

    private TextBox Display;
    private Button Edit;

    private List<object?>? list;

    public override object? Value {
        get => list?.ToArray();
        set
        {
            if (value is string)
                list = new List<object?> { value };
            else if(value is IEnumerable objList)
            {
                list = objList.Cast<object?>().ToList();
            }
            else if (value is ISubQuery)
            {
                list = new();
            }
            else
            {
                list = new List<object?> { value };
            }
            UpdateDisplayText();
        }
    }

    public ArrayValueNode()
    {
        var panel = new DockPanel();

        Display = new TextBox
        {
            VerticalContentAlignment = System.Windows.VerticalAlignment.Center,
            Background = new SolidColorBrush(Colors.LightYellow),
            Margin = new Thickness(0, 0, 5, 0),
            IsEnabled = false
        };
        Edit = new Button
        {
            Content = "Edit",
            Padding = new Thickness(5)
        };
        Edit.Click += Edit_Click;

        Display.SetValue(DockPanel.DockProperty, Dock.Left);
        Edit.SetValue(DockPanel.DockProperty, Dock.Right);

        panel.Children.Add(Edit);
        panel.Children.Add(Display);

        Content = panel;
    }

    public override bool IsEnabled
    {
        get => Display.IsEnabled;
        set
        {
            Display.IsEnabled = value;
            Display.IsReadOnly = !value;
        }
    }

    private void Edit_Click(object sender, RoutedEventArgs e)
    {
        var window = new ArrayValueNodePopup();
        window.SetList<TValueNode>(list ?? new List<object?>());

        if (window.ShowDialog() == true)
        {
            list = window.GetList<TValueNode>();
            UpdateDisplayText();
        }
    }

    private void UpdateDisplayText()
    {
        Display.Text = $"[{(list != null ? string.Join(',', list) : "")}]";
    }
}