#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "WingGraphActions.h"
#include "WingGraphExport.h"
#include "EdGraph/EdGraph.h"
#include "GraphNode_Add.generated.h"


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

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

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

	UPROPERTY(EditAnywhere, meta=(Description="Node type, from GraphNode_SearchTypes"))
	FString Type;

	UPROPERTY(EditAnywhere, meta=(Description="Node X position"))
	int32 PosX = 0;

	UPROPERTY(EditAnywhere, meta=(Description="Node Y position"))
	int32 PosY = 0;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Create nodes using the editor's action database. "
			"Use GraphNode_SearchTypes to find types."));
	}
	virtual void Handle() override
	{
		WingFetcher F(WingOut::Stdout);
		UEdGraph* TargetGraph = F.Walk(GraphPath).Cast<UEdGraph>();
		if (!TargetGraph) return;

		FWingGraphActions GraphActions(TargetGraph);
		TArray<FWingGraphAction*> Results = GraphActions.Search(Type, 2, true);
		if (!WingUtils::CheckExactlyOneNamed(Results.Num(), TEXT("node type"), Type, WingOut::Stdout)) return;

		UEdGraphNode* NewNode = Results[0]->Execute(FVector2D(PosX, PosY));
		if (NewNode)
		{
			WingOut::Stdout.Printf(TEXT("Spawned: %s\n"), *Type);
			WingGraphExport Export(NewNode, false, true);
			WingOut::Stdout.Print(Export.GetOutput());
			return;
		}

		WingOut::Stdout.Printf(TEXT("Failed: %s\n"), *Type);
	}
};
