using System.Runtime.InteropServices;
using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Input;
using Robust.Shared.Maths;

namespace Robust.Client.UserInterface;

[GenerateTypedNameReferences]
internal sealed partial class ProfTreeEntry : Control
{
    private readonly ProfTree _tab;
    private readonly ProfTree.TreeExpand _parentExpand;
    public readonly (int str, int i) Id;

    protected override void StylePropertiesChanged()
    {
        base.StylePropertiesChanged();

        if (!TryGetStyleProperty("arrowColor", out Arrow.Color))
            Arrow.Color = Color.White;

        if (!TryGetStyleProperty("arrowOutline", out Arrow.OutlineColor))
            Arrow.OutlineColor = Color.Black;
    }

    public ProfTreeEntry(
        ProfTree tab,
        ProfTree.TreeExpand parentExpand,
        (int str, int i) id,
        float margin)
    {
        _tab = tab;
        _parentExpand = parentExpand;
        Id = id;

        RobustXamlLoader.Load(this);

        LineContainer.Margin = new Thickness(margin, 0, 0, 0);
    }

    protected internal override void KeyBindDown(GUIBoundKeyEventArgs args)
    {
        if (args.Function != EngineKeyFunctions.UIClick)
            return;

        args.Handle();

        ref var tree = ref CollectionsMarshal.GetValueRefOrAddDefault(_parentExpand.ExpandedItems, Id, out var had);
        if (had)
        {
            if (tree!.Enabled)
            {
                tree.Enabled = false;
                if (tree.ExpandedItems.Count == 0)
                    _parentExpand.ExpandedItems.Remove(Id);
            }
            else
            {
                tree.Enabled = true;
            }
        }
        else
        {
            tree = new ProfTree.TreeExpand();
        }

        _tab.RebuildTree();
    }


}
