#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "Engine/Blueprint.h"
#include "EdGraph/EdGraphNode.h"
#include "GraphNode_SetPositions.generated.h"


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

USTRUCT()
struct FMoveNodeEntry
{
	GENERATED_BODY()

	UPROPERTY()
	FString Node;

	UPROPERTY()
	int32 X = 0;

	UPROPERTY()
	int32 Y = 0;
};


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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Target graph"))
	FString Graph;

	UPROPERTY(EditAnywhere, meta=(Description="Array of {node, x, y} objects"))
	FWingJsonArray Nodes;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Reposition one or more nodes in a Blueprint graph."));
	}
	virtual void Handle() override
	{
		WingFetcher F;
		UEdGraph* TargetGraph = F.Walk(Graph).Cast<UEdGraph>();
		if (!TargetGraph) return;

		int32 SuccessCount = 0;

		for (const TSharedPtr<FJsonValue>& NodeVal : Nodes.Array)
		{
			FMoveNodeEntry Entry;
			if (!FWingProperty::PopulateFromJson(FMoveNodeEntry::StaticStruct(), &Entry, NodeVal)) continue;

			WingFetcher FN(TargetGraph);
			UEdGraphNode* Node = FN.Node(Entry.Node).Cast<UEdGraphNode>();
			if (!Node) continue;

			Node->NodePosX = Entry.X;
			Node->NodePosY = Entry.Y;
			SuccessCount++;
		}

		UWingServer::Printf(TEXT("Moved %d/%d nodes.\n"), SuccessCount, Nodes.Array.Num());
	}
};
