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


#include "LandingZone.h"

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

// Sets default values
ALandingZone::ALandingZone()
{
 	// 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 ALandingZone::BeginPlay()
{
	WaypointWidgetComponent = Cast<UWidgetComponent>(GetComponentByClass(UWidgetComponent::StaticClass()));
	PlayersPawn = GetWorld()->GetFirstPlayerController()->GetPawn();
	
	// Tick updates the waypoints transform base on players location
	if (!IsValid(WaypointWidgetComponent) || !IsValid(PlayersPawn)) SetActorTickEnabled(false);

	Super::BeginPlay();
}

void ALandingZone::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	if (!IsWaypointVisible) return;
	UpdateWaypointTransform();
}

void ALandingZone::UpdateWaypointTransform()
{
	FVector WaypointLoc = WaypointWidgetComponent->GetComponentLocation();
	FVector PlayerLoc = PlayersPawn->GetActorLocation();
    
	// Update rotation
	FVector LocationDiffVector = PlayerLoc - WaypointLoc;
	FRotator LookAtPlayerRotator = LocationDiffVector.Rotation();
	WaypointWidgetComponent->SetWorldRotation(LookAtPlayerRotator);
    
	// Update scale
	double DistanceFromPlayer = LocationDiffVector.Length();
	double ScaleMagnitude = (12.f - 0.15f) / (48000.f - 900.f);
	double ScaleIntercept = 12.f - (48000.f * ScaleMagnitude);
	double ResultingScale = (DistanceFromPlayer * ScaleMagnitude) + ScaleIntercept;
	FVector WaypointScale = FVector(1, ResultingScale, ResultingScale);
	WaypointWidgetComponent->SetWorldScale3D(WaypointScale);
}


void ALandingZone::UpdateAllLandingZones(bool Landing)
{
	TArray<AActor*> AllLandingZones;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), ALandingZone::StaticClass(), AllLandingZones);
	for (auto LZ_Actor : AllLandingZones)
	{
		ALandingZone* LZ = Cast<ALandingZone>(LZ_Actor);
		Landing ? LZ->HideWaypoint() : LZ->ShowWaypoint();
		LZ->IsWaypointVisible = !Landing;
	}
}

void ALandingZone::Interact()
{
	Takeoff();
}

void ALandingZone::InteractPrompt()
{
	
}

void ALandingZone::Land()
{
	AEndlessVendettaCharacter* PlayerChar = Cast<AEndlessVendettaCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn());
	if (!IsValid(PlayerChar)) return;
	UpdateAllLandingZones(true);
	PlayerChar->ExitShip(LZ_ExitTransform);
}

void ALandingZone::Takeoff()
{
	AEndlessVendettaCharacter* PlayerChar = Cast<AEndlessVendettaCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn());
	if (!IsValid(PlayerChar)) return;
	UpdateAllLandingZones(false);
	PlayerChar->EnterShip(LZ_TakeoffTransform);
}

