#pragma once

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


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

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Blueprint name or package path"))
	FString BlueprintPath;

	UPROPERTY(EditAnywhere, meta=(Description="Name of the event dispatcher to delete"))
	FString Dispatcher;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Delete an event dispatcher from a Blueprint."));
	}
	virtual void Handle() override
	{
		WingFetcher F(WingOut::Stdout);
		UBlueprint* BP = F.Walk(BlueprintPath).Cast<UBlueprint>();
		if (!BP) return;

		FBPVariableDescription* Var = WingUtils::FindOneWithExternalID(Dispatcher, BP->NewVariables, TEXT("Dispatcher"), WingOut::Stdout);
		if (!Var) return;
		TObjectPtr<UEdGraph> Graph = WingUtils::FindOneWithExternalID(Dispatcher, BP->DelegateSignatureGraphs, TEXT("Dispatcher Signature Graph"), WingOut::Stdout);
		if (!Graph) return;

		FName VarFName = Var->VarName;

		// Remove the member variable (also destroys referencing nodes)
		FBlueprintEditorUtils::RemoveMemberVariable(BP, VarFName);

		// Remove the signature graph
		FBlueprintEditorUtils::RemoveGraph(BP, Graph, EGraphRemoveFlags::Recompile);

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