/**
 * Copyright 2022-2025 Theai, Inc. dba Inworld AI
 */
#include "Graph/Assets/InworldNodeAsset.h"

#include "Graph/Assets/InworldGraphAsset.h"
#include "Graph/InworldGraph.h"
#include "Graph/Nodes/InworldNode_SubgraphNode.h"

#define LOCTEXT_NAMESPACE "InworldGraphNode"

UInworldNodeAsset::UInworldNodeAsset()
{
}

UInworldNodeAsset::~UInworldNodeAsset()
{
}

UInworldEdgeAsset* UInworldNodeAsset::GetEdge(UInworldNodeAsset* ChildNode)
{
	return Edges.Contains(ChildNode) ? Edges.FindChecked(ChildNode) : nullptr;
}

FText UInworldNodeAsset::GetNodeTitle()
{
	if (NodeTitle.IsEmpty() && IsValid(RuntimeNode))
	{
		NodeTitle = RuntimeNode->GetNodeName();
	}
	return FText::FromString(NodeTitle);
}

#if WITH_EDITOR
bool UInworldNodeAsset::IsNameEditable() const
{
	return true;
}

void UInworldNodeAsset::SetNodeTitle(const FText& NewTitle)
{
	NodeTitle = NewTitle.ToString();
	if (IsValid(RuntimeNode))
	{
		FString NativeNodeId = NodeTitle.Replace(TEXT(" "), TEXT(""));
		RuntimeNode->SetNodeName(NativeNodeId);
	}
}

bool UInworldNodeAsset::CanCreateConnection(UInworldNodeAsset* Other, FText& ErrorMessage)
{
	return true;
}

bool UInworldNodeAsset::CanCreateConnectionTo(UInworldNodeAsset* Other, int32 NumberOfChildrenNodes, FText& ErrorMessage)
{
	return CanCreateConnection(Other, ErrorMessage);
}

bool UInworldNodeAsset::CanCreateConnectionFrom(UInworldNodeAsset* Other, int32 NumberOfParentNodes, FText& ErrorMessage)
{
	return true;
}
void UInworldNodeAsset::CreateRuntimeNode(UInworldGraphAsset* Outer, UInworldGraphAsset* SubGraphAsset)
{
	// create runtime node
	if (NodeClass && Outer && Outer->RuntimeGraph && !RuntimeNode)
	{
		RuntimeNode = NewObject<UInworldNode>(Outer->RuntimeGraph, NodeClass);
		RuntimeNode->IsInGraphEditor = true;
		NodeClassName = NodeClass->GetName();
		NodeClassPath = NodeClass->GetClassPathName().ToString();
		if (UInworldNode_SubgraphNode* SubgraphNode = Cast<UInworldNode_SubgraphNode>(RuntimeNode))
		{
			if (SubGraphAsset)
			{
				SubgraphNode->SetGraphAsset(SubGraphAsset);
			}
		}
	}
}
#endif

bool UInworldNodeAsset::IsLeafNode() const
{
	return ChildrenNodes.Num() == 0;
}

bool UInworldNodeAsset::IsRootNode() const
{
	return ParentNodes.Num() == 0;
}

#undef LOCTEXT_NAMESPACE
