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

#include "Graph/InworldNode.h"

#include "InworldRuntimeSubsystem.h"
#include "InworldRuntimeUtils.h"

void UInworldNode::InitializeNode(const FString& InstanceData)
{
	this->AddToRoot();
	FInworldRuntimeUtils::DeserializeInstance(this, InstanceData);
	if (auto* Subsystem = UInworldRuntimeSubsystem::Get())
	{
		Subsystem->RegisterNode(this);
	}
}

void UInworldNode::DestroyNode()
{
	bPendingDestroy = true;
	if (auto* Subsystem = UInworldRuntimeSubsystem::Get())
	{
		Subsystem->UnregisterNode(this);
	}
	this->RemoveFromRoot();
	this->ConditionalBeginDestroy();
}

void UInworldNode::BeginDestroy()
{
	if (bPendingDestroy)
	{
		UE_LOG(LogInworldGraph, Log, TEXT("UInworldNode::BeginDestroy - %s"), *NodeName);
	}
	Super::BeginDestroy();
}

const FString& UInworldNode::GetDescription()
{
	return NodeDescription;
}

TArray<UFunction*> UInworldNode::GetProcessFunctions() const
{
	TArray<UFunction*> Functions;
	for (TFieldIterator<UFunction> FuncIt(GetClass(), EFieldIteratorFlags::IncludeSuper); FuncIt; ++FuncIt)
	{
		if (UFunction* const Function = *FuncIt; Function != nullptr && Function->GetName().StartsWith(TEXT("Process")))
		{
			Functions.Add(Function);
		}
	}
	return Functions;
}
