// Copyright (c) 2024 Codemongous LLC. All Rights Reserved.

#include "SCW_USceneComponent.h"
#include "Components/SceneComponent.h"
#include "SourcifyCoreUEWrapperModule.h"

using namespace Sourcify;

SCW_USceneComponent::SCW_USceneComponent(USceneComponent* InSceneComponent) : SCW_UActorComponent(InSceneComponent), SceneComponent(InSceneComponent)
{

}

bool SCW_USceneComponent::AttachToComponent(shared_ptr<ISCW_USceneComponent> InParent, SCW_EAttachmentTransformRules AttachmentRules, wstring InSocketName/* = L"None"*/ /*NAME_None*/) const
{
	if (InParent)
	{
		if (USceneComponent* Parent = dynamic_cast<SCW_USceneComponent*>(InParent.get())->ToUSceneComponent())
		{
			FAttachmentTransformRules AttachmentTransformRules = FAttachmentTransformRules::KeepRelativeTransform;
			switch (AttachmentRules)
			{
			case SCW_EAttachmentTransformRules::KeepRelativeTransform:
				AttachmentTransformRules = FAttachmentTransformRules::KeepRelativeTransform;
				break;
			case SCW_EAttachmentTransformRules::KeepWorldTransform:
				AttachmentTransformRules = FAttachmentTransformRules::KeepWorldTransform;
				break;
			case SCW_EAttachmentTransformRules::SnapToTargetNotIncludingScale:
				AttachmentTransformRules = FAttachmentTransformRules::SnapToTargetNotIncludingScale;
				break;
			case SCW_EAttachmentTransformRules::SnapToTargetIncludingScale:
				AttachmentTransformRules = FAttachmentTransformRules::SnapToTargetIncludingScale;
				break;
			default:
				AttachmentTransformRules = FAttachmentTransformRules::KeepRelativeTransform;
				break;
			}

			return SceneComponent->AttachToComponent(Parent, AttachmentTransformRules, FName(InSocketName.c_str()));
		}
	}

	return false;
}

ISCW_USceneComponentPtr SCW_USceneComponent::GetAttachParent() const
{
	if (USceneComponent* AttachParent = SceneComponent->GetAttachParent())
	{
		return FSourcifyCoreUEWrapper::Get().Wrap(*AttachParent);
	}
	
	return nullptr;
}

wstring SCW_USceneComponent::GetAttachSocketName() const
{
	return *SceneComponent->GetAttachSocketName().ToString();
}

SCW_FTransform SCW_USceneComponent::GetRelativeTransform() const
{
	const FTransform& RelativeTransform = SceneComponent->GetRelativeTransform();
	return SCW_FTransform
	(
		{ RelativeTransform.GetRotation().X, RelativeTransform.GetRotation().Y, RelativeTransform.GetRotation().Z, RelativeTransform.GetRotation().W },
		{ RelativeTransform.GetLocation().X, RelativeTransform.GetLocation().Y, RelativeTransform.GetLocation().Z },
		{ RelativeTransform.GetScale3D().X, RelativeTransform.GetScale3D().Y, RelativeTransform.GetScale3D().Z }
	);
}

USceneComponent* SCW_USceneComponent::ToUSceneComponent() const
{
	return SceneComponent;
}
