#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "EdGraph/EdGraph.h"
#include "EdGraph/EdGraphPin.h"
#include "GraphPin_Disconnect.generated.h"


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

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

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

	UPROPERTY(EditAnywhere, meta=(Description="Pin ID strings"))
	FWingRestOfArgv Pins;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Disconnect all connections on the specified pins. "
			"Pin IDs use fetcher path syntax relative to the graph, eg: "
			"node:K2Node_CallFunction_0,pin:ReturnValue"));
	}
	virtual void Handle() override
	{
		WingFetcher F(WingOut::Stdout);
		UEdGraph* G = F.Walk(GraphPath).Cast<UEdGraph>();
		if (!G) return;

		int32 SuccessCount = 0;
		int32 TotalDisconnected = 0;

		for (const FString& PinPath : Pins.Argv)
		{
			WingFetcher FP(G, WingOut::Stdout);
			UWingGraphPinRef* PinRef = FP.Walk(PinPath).Cast<UWingGraphPinRef>();
			if (!PinRef) continue;
			UEdGraphPin* Pin = WingUtils::CheckGetPin(PinRef->Node, PinRef->PinName, WingOut::Stdout);
			if (!Pin) continue;

			int32 DisconnectedCount = Pin->LinkedTo.Num();
			if (DisconnectedCount > 0)
			{
				Pin->BreakAllPinLinks(true);
			}

			WingOut::Stdout.Printf(TEXT("Disconnected %d link(s) from %s.%s\n"),
				DisconnectedCount,
				*WingUtils::FormatName(Pin->GetOwningNode()), *WingUtils::FormatName(Pin));
			SuccessCount++;
			TotalDisconnected += DisconnectedCount;
		}

		WingOut::Stdout.Printf(TEXT("Done: %d/%d succeeded, %d links broken.\n"),
			SuccessCount, Pins.Argv.Num(), TotalDisconnected);
	}
};
