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


#include "VisionLinkTutorial.h"

#include "EndlessVendetta/EndlessVendettaCharacter.h"
#include "Kismet/KismetMathLibrary.h"

void AVisionLinkTutorial::BeginPlay()
{
	Super::BeginPlay();
	GadgetManager = Cast<AEndlessVendettaCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn())->GadgetManager;
	SpawnNewWaypoint(GoToAreaWaypointLoc, GoToAreaWaypointDesc);
}

void AVisionLinkTutorial::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);

	if (!PlayerInTutorialZone)
	{
		if (PlayerWasInTutZone) SpawnNewWaypoint(GoToAreaWaypointLoc, GoToAreaWaypointDesc);
		PlayerWasInTutZone = false;
		return;
	}

	if (!PlayerWasInTutZone) SpawnNewWaypoint(LookAtTargetWaypointLoc, LookAtTargetWaypointDesc);
	PlayerWasInTutZone = true;
	
	// Check if players recon gadget (vision link) is in active
	if (!GadgetManager->ReconInUse()) return;

	// Check if the player is roughly looking at their target
	APawn* PlayerPawn = GetWorld()->GetFirstPlayerController()->GetPawn();
	FRotator LookAtRot = UKismetMathLibrary::FindLookAtRotation(PlayerPawn->GetActorLocation(), TargetLoc);
	FRotator PlayersRotator = PlayerPawn->GetActorRotation();
	// Keep all yaw values between -180 and 180 to simplify the comparison
	float DesiredtYaw = LookAtRot.Yaw - (LookAtRot.Yaw > 180 ? 360 : 0);
	float PlayersYaw = PlayersRotator.Yaw - (PlayersRotator.Yaw > 180 ? 360 : 0);
	// Do nothing if players yaw is off by more than 45 degrees
	if (FMath::Abs(DesiredtYaw - PlayersYaw) > 45) return;

	
	SpawnNewWaypoint(ResultWaypointLoc, ResultWaypointDesc);
	FTimerHandle TimerHandle;
	GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &AVisionLinkTutorial::FinishedTutorial, 7.5);
	SetActorTickEnabled(false);
}





