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

#include "Components/InworldPlayerComponent.h"

#include "Components/InworldCharacterComponent.h"
#include "InworldCharacter.h"

void UInworldPlayerComponent::SetConversationTarget(TScriptInterface<IInworldConversationTarget> NewConversationTarget)
{
	if (ConversationTarget == NewConversationTarget)
	{
		return;
	}

	if (UInworldCharacterComponent* CharacterComponent = Cast<UInworldCharacterComponent>(NewConversationTarget.GetObject()))
	{
		if (CharacterComponent->IsInConversationGroup())
		{
			UE_LOG(LogInworldCharacter, Warning,
				TEXT("UInworldPlayerComponent::SetConversationTarget - failed to set conversation target to character (%s)."
					 " You can not target characters in a conversation group directly."),
				*CharacterComponent->GetId());
			return;
		}
	}
	Super::SetConversationTarget(NewConversationTarget);
}

void UInworldPlayerComponent::SendMessage(const FInworldDataHandle& Message)
{
	if (IsValid(ConversationTarget.GetObject()))
	{
		if (UInworldCharacterComponent* CharacterComponent = Cast<UInworldCharacterComponent>(ConversationTarget.GetObject()))
		{
			if (CharacterComponent->IsInConversationGroup())
			{
				UE_LOG(LogInworldCharacter, Warning,
					TEXT("UInworldPlayerComponent::SendMessage - failed to send message to character (%s)."
						 " You can not message characters in a conversation group directly."),
					*CharacterComponent->GetId());
				return;
			}
		}
		IInworldConversationTarget::Execute_Interrupt(ConversationTarget.GetObject());
		IInworldConversationTarget::Execute_SendPlayerMessage(ConversationTarget.GetObject(), Message, PlayerProfile);
	}
	else
	{
		UE_LOG(LogInworldCharacter, Warning,
			TEXT("UInworldBasePlayerComponent::SendMessage - failed to send message."
				 " Invalid conversation target."))
	}
}

void UInworldPlayerComponent::SendTrigger(FName GoalName, const TMap<FString, FString> Parameters)
{
	if (IsValid(ConversationTarget.GetObject()))
	{
		FInworldCharacterTrigger TriggerData;
		TriggerData.GoalName = GoalName;
		TriggerData.Parameters = Parameters;
		if (UInworldCharacterComponent* CharacterComponent = Cast<UInworldCharacterComponent>(ConversationTarget.GetObject()))
		{
			CharacterComponent->SendMessage(FInworldData_Struct(TriggerData));
		}
		else
		{
			UE_LOG(LogInworldCharacter, Warning,
				TEXT("UInworldPlayerComponent::SendTrigger - failed to send trigger."
					 " Unsupported conversation target."))
		}
	}
	else
	{
		UE_LOG(LogInworldCharacter, Warning,
			TEXT("UInworldPlayerComponent::SendTrigger - failed to send trigger."
				 " Invalid conversation target."))
	}
}
