#pragma once

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


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

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

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

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

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

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

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

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