#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "Engine/Blueprint.h"
#include "EdGraph/EdGraph.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "BlueprintGraph_Delete.generated.h"


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

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Path to the graph, e.g. /Game/MyBP,graph:MyFunction"))
	FString Graph;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Delete a function or macro graph from a Blueprint."));
	}
	virtual void Handle() override
	{
		WingFetcher F;
		UEdGraph* FoundGraph = F.Walk(Graph).Cast<UEdGraph>();
		if (!FoundGraph) return;

		UBlueprint* BP = FBlueprintEditorUtils::FindBlueprintForGraph(FoundGraph);
		if (!BP)
		{
			UWingServer::Print(TEXT("ERROR: Could not find owning blueprint for this graph.\n"));
			return;
		}

		if (!BP->FunctionGraphs.Contains(FoundGraph) && !BP->MacroGraphs.Contains(FoundGraph))
		{
			UWingServer::Printf(TEXT("ERROR: %s is not a function or macro graph.\n"), *WingUtils::FormatName(FoundGraph));
			return;
		}

		FBlueprintEditorUtils::RemoveGraph(BP, FoundGraph, EGraphRemoveFlags::Recompile);

		UWingServer::Printf(TEXT("Deleted graph from %s\n"), *WingUtils::FormatName(BP));
	}
};
