// (C) MAI 2020. All rights reserved.

#include "Actor/BaseMotioNController.h"

#include "Actor/BaseMotionController.h"
#include "EngineUtils.h"

#include <XRMotionControllerBase.h>

// Sets default values
ABaseMotionController::ABaseMotionController()
{
	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));

	MotionControllerComponent = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("MotionController"));
	MotionControllerComponent->SetupAttachment(RootComponent);
	MotionControllerComponent->SetRelativeLocation(FVector(0, 0, 0));

	ControllerSkeletalMeshComponent = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("ControllerMesh"));
	ControllerSkeletalMeshComponent->SetupAttachment(MotionControllerComponent);
	ControllerSkeletalMeshComponent->SetCanEverAffectNavigation(false);
	
	// #TODO collisions on controller skelmeshes
	// 	ControllerSkeletalMeshComponent->SetCollisionObjectType(ECC_WorldDynamic);
	// 	ControllerSkeletalMeshComponent->SetCollisionProfileName("WorldDynamic");
	ControllerSkeletalMeshComponent->SetCollisionEnabled(ECollisionEnabled::NoCollision);

}

void ABaseMotionController::ScaleMesh(const float InScaleChangeRatio)
{
	if (ControllerSkeletalMeshComponent)
	{
		ControllerSkeletalMeshComponent->SetRelativeScale3D(
			ControllerSkeletalMeshComponent->GetRelativeScale3D() / InScaleChangeRatio);
	}
}

void ABaseMotionController::ResetMeshScale()
{
	if (ControllerSkeletalMeshComponent)
	{
		ControllerSkeletalMeshComponent->SetRelativeScale3D(FVector(1));
	}
}

void ABaseMotionController::SetupInput(UInputComponent* InInputComponent)
{
	if (bIsInRightHand)
	{
		MotionControllerComponent->SetTrackingMotionSource(FXRMotionControllerBase::RightHandSourceId);
		InInputComponent->BindAction("Right_Grip", IE_Pressed, this, &ABaseMotionController::OnGripPressed);
		InInputComponent->BindAction("Right_Grip", IE_Released, this, &ABaseMotionController::OnGripReleased);
	}
	else
	{
		MotionControllerComponent->SetTrackingMotionSource(FXRMotionControllerBase::LeftHandSourceId);
		InInputComponent->BindAction("Left_Grip", IE_Pressed, this, &ABaseMotionController::OnGripPressed);
		InInputComponent->BindAction("Left_Grip", IE_Released, this, &ABaseMotionController::OnGripReleased);
	}
}

// Called when the game starts or when spawned
void ABaseMotionController::BeginPlay()
{
	Super::BeginPlay();
}

FVector ABaseMotionController::GetControllerLocation()
{
	if (MotionControllerComponent)
	{
		return MotionControllerComponent->GetRelativeLocation();
	}
	return FVector(0, 0, 0);
}

FRotator ABaseMotionController::GetControllerRotation()
{
	if (MotionControllerComponent)
	{
		return MotionControllerComponent->GetRelativeRotation();
	}
	return FRotator(0, 0, 0);
}
