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

#include "NpcPawnMovement.h"
#include "GameFramework/Actor.h"
#include "Engine/World.h"
#include "DrawDebugHelpers.h"
#include "Components/CapsuleComponent.h"

UNpcPawnMovement::UNpcPawnMovement()
{
	PrimaryComponentTick.bCanEverTick = true;
	NavMovementProperties.bUseFixedBrakingDistanceForPaths = true;
	NavMovementProperties.bUseAccelerationForPaths = true;
	NavAgentProps.bCanWalk = true;
	NavAgentProps.bCanFly = false;
	NavAgentProps.bCanSwim = false;
}

void UNpcPawnMovement::BeginPlay()
{
	Super::BeginPlay();
	
	OwnerCapsuleComp = GetOwner()->GetComponentByClass<UCapsuleComponent>();
}

void UNpcPawnMovement::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
	SnapToGround();
}

void UNpcPawnMovement::SnapToGround()
{
	if (!UpdatedComponent || !OwnerCapsuleComp)
		return;
	
	const FVector Start = UpdatedComponent->GetComponentLocation();
	const FVector End = Start - FVector(0, 0, GroundTraceDistance);
	
	FHitResult Hit;
	FCollisionQueryParams TraceParams;
	TraceParams.AddIgnoredActor(GetOwner());
	
	bool bHit = GetWorld()->LineTraceSingleByChannel(
		Hit,
		Start,
		End,
		ECC_WorldStatic,
		TraceParams);
	
	if (bHit)
	{
		FVector NewLocation = Hit.Location;
		NewLocation.Z += OwnerCapsuleComp->GetScaledCapsuleHalfHeight();
		UpdatedComponent->SetWorldLocation(NewLocation);
	}
}

void UNpcPawnMovement::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed)
{
	//Super::RequestDirectMove(MoveVelocity, bForceMaxSpeed);
	FVector LineEnd = GetOwner()->GetActorLocation() + (MoveVelocity * 100.f);
	DrawDebugLine(GetWorld(), GetOwner()->GetActorLocation(),  LineEnd ,FColor::Red, false, 1, 0, 1);
	FVector DesiredMovement = MoveVelocity;
	DesiredMovement.Z = 0.0f;
	AddInputVector(DesiredMovement.GetSafeNormal());
}

bool UNpcPawnMovement::CanStartPathFollowing() const
{
	return true;
}

bool UNpcPawnMovement::CanStopPathFollowing() const
{
	return true;
}

void UNpcPawnMovement::RequestPathMove(const FVector& MoveInput)
{
	AddInputVector(MoveInput, true);
}
