// Fill out your copyright notice in the Description page of Project Settings.


#include "VentuzActorTransformSync.h"
#include "GameFramework/Actor.h"
#include "VentuzPluginModule.h"
#include "ComponentUtils.h"

uint GetLowerStringHash( FString string );


// Sets default values for this component's properties
UVentuzActorTransformSync::UVentuzActorTransformSync()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	PrimaryComponentTick.bCanEverTick = true;

	// ...
}


// Called when the game starts
void UVentuzActorTransformSync::BeginPlay()
{
	Super::BeginPlay();

	SetTickGroup(ETickingGroup::TG_PostPhysics);

	// ...
	
}


// Called every frame
void UVentuzActorTransformSync::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    //TRACE_CPUPROFILER_EVENT_SCOPE( TEXT( "UVentuzActorTransformSync::TickComponent" ) );
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	auto* ownerActor = GetOwner();
/*
	auto* rootComponent = owner->GetRootComponent();
	auto* attachParent = rootComponent->GetAttachParent();
	AActor* ownerActor = attachParent->GetOwner();
*/

    FVentuzPlugin& ventuzPlugin = FModuleManager::LoadModuleChecked<FVentuzPlugin>( "VentuzPlugin" );
    uint hash = GetLowerStringHash( ventuzAxisNodeName );

	if ( syncDirection == VentuzCommunicationDirection::ToVentuz )
	{
        if (!relativeTransform)
        {
            //const FTransform& transform = ownerActor->GetActorTransform();
            ventuzPlugin.SendTransformValue(hash, ownerActor->GetActorTransform());
        }
        else
        {
            //ownerActor->GetRootComponent()->GetRelativeTransform();
            //auto attachedParent = ComponentUtils::GetAttachedParent(ownerActor);
            auto parent = ownerActor->GetAttachParentActor();
            FTransform relative = ownerActor->GetActorTransform();
            
            if (parent)
                relative = relative.GetRelativeTransform(parent->GetActorTransform());

            ventuzPlugin.SendTransformValue(hash, relative);
        }
	}
	else
	{
		bool isAvailable = false;
		FTransform transform = ventuzPlugin.GetTransformValue( hash, isAvailable );

		if ( isAvailable )
		{
            if (!relativeTransform)
                ownerActor->SetActorTransform(transform);
            else
                ownerActor->SetActorRelativeTransform(transform);
		}
	}
}

