/**
 * Copyright 2022-2025 Theai, Inc. dba Inworld AI
 */

#include "K2Node_InworldCreateErrorData.h"

#include "BlueprintActionDatabaseRegistrar.h"
#include "BlueprintNodeSpawner.h"
#include "InworldBlueprintFunctionLibrary.h"

void UK2Node_InworldCreateErrorData::GetMenuActions(FBlueprintActionDatabaseRegistrar& ActionRegistrar) const
{
	Super::GetMenuActions(ActionRegistrar);
	UClass* Action = GetClass();
	if (ActionRegistrar.IsOpenForRegistration(Action))
	{
		auto CustomizeLambda = [](UEdGraphNode* NewNode, bool bIsTemplateNode, const FName FunctionName)
		{
			UK2Node_InworldCreateErrorData* Node = CastChecked<UK2Node_InworldCreateErrorData>(NewNode);
			UFunction* Function = UInworldBlueprintFunctionLibrary::StaticClass()->FindFunctionByName(FunctionName);
			check(Function);
			Node->SetFromFunction(Function);
		};

		UBlueprintNodeSpawner* GetNodeSpawner = UBlueprintNodeSpawner::Create(GetClass());
		check(GetNodeSpawner != nullptr);
		GetNodeSpawner->CustomizeNodeDelegate = UBlueprintNodeSpawner::FCustomizeNodeDelegate::CreateStatic(
			CustomizeLambda, GET_FUNCTION_NAME_CHECKED(UInworldBlueprintFunctionLibrary, CreateInworldDataError));
		ActionRegistrar.AddBlueprintAction(Action, GetNodeSpawner);
	}
}

void UK2Node_InworldCreateErrorData::PinDefaultValueChanged(UEdGraphPin* ChangedPin)
{
	Super::PinDefaultValueChanged(ChangedPin);
	if (ChangedPin->PinName == "InworldDataStructType")
	{
		if (ChangedPin->LinkedTo.Num() == 0)
		{
			UEdGraphPin* DataPin = FindPinChecked(FName{"Data"});
			if (DataPin->SubPins.Num() > 0)
			{
				GetSchema()->RecombinePin(DataPin);
			}
			RefreshOutputStructType();
		}
	}
}

void UK2Node_InworldCreateErrorData::PostReconstructNode()
{
	Super::PostReconstructNode();
	RefreshOutputStructType();
}

void UK2Node_InworldCreateErrorData::ClearCachedBlueprintData(UBlueprint* Blueprint)
{
	Super::ClearCachedBlueprintData(Blueprint);
	RefreshOutputStructType();
}

void UK2Node_InworldCreateErrorData::RefreshOutputStructType()
{
	auto GetPinForMe = [this](FName PinName)
	{
		UEdGraphPin* Pin = FindPinChecked(PinName);
		return Pin;
	};

	UEdGraphPin* DataPin = FindPinChecked(FName{"Data"});
	UEdGraphPin* StructTypePin = FindPinChecked(FName{"InworldDataStructType"});

	if (StructTypePin->DefaultObject != DataPin->PinType.PinSubCategoryObject)
	{
		DataPin->PinType.PinSubCategoryObject = StructTypePin->DefaultObject;
		DataPin->PinType.PinCategory =
			(StructTypePin->DefaultObject == nullptr) ? UEdGraphSchema_K2::PC_Wildcard : UEdGraphSchema_K2::PC_Struct;
	}
}
