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


#include "WaypointActor.h"

#include "Engine/EngineTypes.h"
#include "EndlessVendetta/EndlessVendettaCharacter.h"

// Sets default values
AWaypointActor::AWaypointActor()
{
 	// 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;
}

void AWaypointActor::SetupWaypoint_Implementation(UTexture2D* Icon, const FString& Desc)
{
	SetActorTickInterval(0.05);
	AActor* PlayerActor = Cast<AActor>(GetWorld()->GetFirstPlayerController()->GetPawn());
	PlayersCam = Cast<UCameraComponent>(PlayerActor->GetComponentByClass(UCameraComponent::StaticClass()));
	ScalingMagnitude = (ScaleAtMaxDist - ScaleAtMinDist) / (MaxDist - MinDist);
	ScalingY_Intercept = ScaleAtMaxDist - (MaxDist * ScalingMagnitude);
    
	MiniWaypoint = CreateWidget<UMiniWaypoint>(GetWorld(), MiniWaypointClass);
	MiniWaypoint->AddToViewport(0);
	MiniWaypoint->WorldLoc = this->GetActorLocation();
	MiniWaypoint->PlayerController = GetWorld()->GetFirstPlayerController();
	MiniWaypoint->SetIcon(Icon);
}

// Called every frame
void AWaypointActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	UpdateScaleAndRotation();
	if (SightCheck())
	{
		UpdateVisibility(true);
		MiniWaypoint->UpdateVisibility(false);
		return;
	}
	UpdateVisibility(false);
	MiniWaypoint->UpdateVisibility(true);
}

bool AWaypointActor::SightCheck()
{
	FHitResult OutHit;
	FCollisionObjectQueryParams ObjectQueryParams;
	ObjectQueryParams.AddObjectTypesToQuery(ECollisionChannel::ECC_GameTraceChannel2);
	FVector LT_Start = PlayersCam->GetComponentLocation();
	FVector LT_End = LT_Start + (PlayersCam->GetForwardVector() * WaypointFocusDistance);
	if (GetWorld()->LineTraceSingleByObjectType(OutHit, LT_Start, LT_End, ObjectQueryParams) && OutHit.GetActor()->GetUniqueID() == this->GetUniqueID()) return true;
	return false;
}

void AWaypointActor::UpdateScaleAndRotation()
{
	if (!PlayersCam) return;

	FVector WaypointLoc = GetActorLocation();
	FVector PlayerCamLoc = PlayersCam->GetComponentLocation();
    	
	FRotator NewRot = UKismetMathLibrary::FindLookAtRotation(WaypointLoc, PlayerCamLoc);
	SetActorRotation(NewRot);
    
	float DistanceToPlayer = FVector::Distance(WaypointLoc, PlayerCamLoc);
	// S for Scale
	float S = (DistanceToPlayer * ScalingMagnitude) + ScalingY_Intercept;
	S = FMath::Clamp(S, ScaleAtMinDist, ScaleAtMaxDist);
	SetActorScale3D(FVector(1.f, S, S));
}

void AWaypointActor::Destroyed()
{
	if (IsValid(MiniWaypoint)) MiniWaypoint->RemoveFromParent();
	Super::Destroyed();
}


