#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingProperty.h"
#include "WingUtils.h"
#include "Engine/Blueprint.h"
#include "EdGraph/EdGraph.h"
#include "EdGraph/EdGraphPin.h"
#include "GraphPin_Disconnect.generated.h"


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

USTRUCT()
struct FDisconnectPinEntry
{
	GENERATED_BODY()

	UPROPERTY()
	FString Pin;

	UPROPERTY(meta=(Optional))
	FString TargetPin;
};


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

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

	UPROPERTY(EditAnywhere, meta=(Description="Array of {pin, targetPin?} objects. If targetPin is omitted, all connections on the pin are broken."))
	FWingJsonArray Disconnections;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Disconnect pins in a graph (Blueprint or Material). "
			"Can disconnect a specific link or all links on a pin."));
	}
	virtual void Handle() override
	{
		WingFetcher F;
		UEdGraph* G = F.Walk(Graph).Cast<UEdGraph>();
		if (!G) return;

		int32 SuccessCount = 0;
		int32 TotalDisconnected = 0;

		for (const TSharedPtr<FJsonValue>& DiscVal : Disconnections.Array)
		{
			FDisconnectPinEntry Entry;
			if (!FWingProperty::PopulateFromJson(FDisconnectPinEntry::StaticStruct(), &Entry, DiscVal)) continue;

			WingFetcher FP(G);
			UEdGraphPin* Pin = FP.Walk(Entry.Pin).Cast<UEdGraphPin>();
			if (!Pin) continue;

			int32 DisconnectedCount = 0;

			if (!Entry.TargetPin.IsEmpty())
			{
				WingFetcher FT(G);
				UEdGraphPin* Target = FT.Walk(Entry.TargetPin).Cast<UEdGraphPin>();
				if (!Target) continue;

				if (!Pin->LinkedTo.Contains(Target))
				{
					UWingServer::Printf(TEXT("Error: %s.%s is not connected to %s.%s\n"),
						*WingUtils::FormatName(Pin->GetOwningNode()), *WingUtils::FormatName(Pin),
						*WingUtils::FormatName(Target->GetOwningNode()), *WingUtils::FormatName(Target));
					continue;
				}

				Pin->BreakLinkTo(Target);
				DisconnectedCount = 1;
			}
			else
			{
				DisconnectedCount = Pin->LinkedTo.Num();
				if (DisconnectedCount > 0)
				{
					Pin->BreakAllPinLinks(true);
				}
			}

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

		UWingServer::Printf(TEXT("Done: %d/%d succeeded, %d links broken.\n"),
			SuccessCount, Disconnections.Array.Num(), TotalDisconnected);
	}
};
