#pragma once

#include "CoreMinimal.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingToolMenu.h"
#include "WingServer.h"
#include "ToolMenus.h"
#include "GraphNode_ChooseMenu.generated.h"


// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

UCLASS()
class UWing_GraphNode_ChooseMenu : public UWingHandler
{
	GENERATED_BODY()

public:
	UPROPERTY(EditAnywhere, meta=(Description="Target node"))
	FString NodePath;

	UPROPERTY(EditAnywhere, meta=(Description="Menu item as shown by GraphNode_ShowMenu"))
	FString Item;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Execute a context menu action on a node or pin. "
			"Supports SplitStructPin, AddPin, AddArrayElementPin, etc. "
			"Use GraphNode_ShowMenu to see available actions. "));
	}
private:
	virtual void Handle() override
	{
		WingFetcher F(WingOut::Stdout);
		UEdGraphNode* NodeObj = F.Walk(NodePath).Cast<UEdGraphNode>();
		if (!NodeObj) return;

		FToolMenuContext Context;
		TArray<FToolMenuEntry> Entries = WingToolMenu::GetMenuItems(NodeObj, Context);
		for (FToolMenuEntry &Entry : Entries)
		{
			FString LabelText = Entry.Label.Get().ToString();
			if (!LabelText.Equals(Item, ESearchCase::IgnoreCase))
				continue;

			if (WingToolMenu::Execute(Entry, Context))
			{
				WingOut::Stdout.Printf(TEXT("Executed: %s\n"), *LabelText);
			}
			else
			{
				WingOut::Stdout.Printf(TEXT("ERROR: Action '%s' cannot execute (greyed out)\n"), *LabelText);
			}
			return;
		}

		WingOut::Stdout.Printf(TEXT("ERROR: Menu item '%s' not found. Use GraphNode_ShowMenu to see available items.\n"), *Item);
	}
};
