// Copyright (c) 2024 Codemongous LLC. All Rights Reserved.

#include "SCW_UEdGraphSchema.h"
#include "EdGraph/EdGraph.h"
#include "EdGraph/EdGraphSchema.h"
#include "SourcifyCoreUEWrapperModule.h"
#include "SCW_UEdGraphPin.h"

using namespace Sourcify;

SCW_UEdGraphSchema::SCW_UEdGraphSchema(UEdGraphSchema* InEdGraphSchema) : SCW_UObject(InEdGraphSchema), EdGraphSchema(InEdGraphSchema)
{

}

UEdGraphSchema* SCW_UEdGraphSchema::ToUEdGraphSchema() const
{
	return EdGraphSchema;
}

ISCW_UEdGraphSchemaPtr SCW_UEdGraphSchema::ToUEdGraphSchemaPtr()
{
	return GetSharedThisAs<SCW_UEdGraphSchema>();
}

ISCW_UEdGraphSchemaConstPtr SCW_UEdGraphSchema::ToUEdGraphSchemaPtr() const
{
	return GetSharedThisAs<SCW_UEdGraphSchema>();
}

bool SCW_UEdGraphSchema::TryCreateConnection(ISCW_UEdGraphPinPtr A, ISCW_UEdGraphPinPtr B) const
{
	UEdGraphPin* PinA = dynamic_cast<SCW_UEdGraphPin*>(A.get())->ToUEdGraphPin();
	UEdGraphPin* PinB = dynamic_cast<SCW_UEdGraphPin*>(B.get())->ToUEdGraphPin();
	check(PinA != PinB);
	
// #if SOURCIFY_DEBUG
// 	UE_LOG(LogTemp, Warning, TEXT("TryCreateConnection from %s to %s | %s to %s"), *PinA->PinName.ToString(), *PinB->PinName.ToString(), *PinA->PinId.ToString(), *PinB->PinId.ToString());
// 	UE_LOG(LogTemp, Warning, TEXT("\t%s -> %s"), *PinA->GetOwningNode()->GetNodeTitle(ENodeTitleType::ListView).ToString(), *PinB->GetOwningNode()->GetNodeTitle(ENodeTitleType::ListView).ToString());
// 	UE_LOG(LogTemp, Warning, TEXT("\t%s"), *PinA->GetOwningNode()->GetGraph()->GetPackage()->GetName());
// #endif

	bool result = EdGraphSchema->TryCreateConnection(PinA, PinB);

// #if SOURCIFY_DEBUG
// 	for (UEdGraphPin* LinkedPin : PinA->LinkedTo)
// 	{
// 		UE_LOG(LogTemp, Warning, TEXT("\t\tLinked pin: %s - %s"), *LinkedPin->PinName.ToString(), *LinkedPin->PinId.ToString());
// 		if (!LinkedPin->GetOwningNode()->GetGraph()->Nodes.Contains(LinkedPin->GetOwningNode()))
// 		{
// 			UE_LOG(LogTemp, Warning, TEXT("\t\t\tDESTROYED_NODE%s"), PinB->PinId == LinkedPin->PinId ? TEXT(" - {NEWLY ADDED PIN}") : TEXT(""));
// 		}
// 	}
// #endif

	return result;
}

void SCW_UEdGraphSchema::SplitPin(ISCW_UEdGraphPinPtr Pin, bool bNotify) const
{
	UEdGraphPin* PinToSplit = dynamic_cast<SCW_UEdGraphPin*>(Pin.get())->ToUEdGraphPin();
	EdGraphSchema->SplitPin(PinToSplit, bNotify);
}

void SCW_UEdGraphSchema::RecombinePin(ISCW_UEdGraphPinPtr Pin) const
{
	UEdGraphPin* PinToRecombine = dynamic_cast<SCW_UEdGraphPin*>(Pin.get())->ToUEdGraphPin();
	EdGraphSchema->RecombinePin(PinToRecombine);
}