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


#include "MiniWaypoint.h"


void UMiniWaypoint::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
	Super::NativeTick(MyGeometry, InDeltaTime);

	if (!IsValid(IconCanvasPanelSlot) || !IsValid(PlayerController)) return;

	FVector2D ScreenLoc;
	PlayerController->ProjectWorldLocationToScreen(WorldLoc, ScreenLoc);

	float TargetYaw = (WorldLoc - PlayerController->GetPawn()->GetActorLocation()).Rotation().Yaw;
	float PlayerYaw = PlayerController->GetControlRotation().Yaw;
	if (TargetYaw < 0 ) TargetYaw += 360;
	
	ArrowImage->SetRenderTransformAngle(TargetYaw - PlayerYaw);
	
	// Check if waypoint is outside of players vision frustum
	if (FMath::IsNearlyZero(ScreenLoc.X) && FMath::IsNearlyZero(ScreenLoc.Y) && !FMath::IsNearlyZero(IconCanvasPanelSlot->GetPosition().X))//(FMath::IsWithin(ScreenLoc.X, -0.01, 0.01) && FMath::IsWithin(ScreenLoc.Y, -0.01, 0.01))
	{
		// Check if waypoint is closer to the players right
		bool TargetOnTheRight;
		if (PlayerYaw >= TargetYaw)
		{
			TargetOnTheRight = FMath::Abs(TargetYaw - PlayerYaw) >= 180;
		}
		else
		{
			TargetOnTheRight = TargetYaw - PlayerYaw <= 180;
		}

		FVector2D NewPos = IconCanvasPanelSlot->GetPosition();
		if ((TargetOnTheRight && NewPos.X < 0) || (!TargetOnTheRight && NewPos.X > 0)) NewPos.X  *= -1;

		IconCanvasPanelSlot->SetPosition(NewPos);
		return;
	}
	
	FVector2d ViewPortSize;
	GEngine->GameViewport->GetViewportSize(ViewPortSize);
	float ViewportHalfX = ViewPortSize.X / 2.f;
	float ViewportHalfY = ViewPortSize.Y / 2.f;

	// Centers the icon
	ScreenLoc.X -= ViewportHalfX;
	ScreenLoc.Y -= ViewportHalfY;

	float ViewportMarginX = ViewportHalfX * 0.8f;
	float ViewportMarginY = ViewportHalfY * 0.6f;

	ScreenLoc.X = FMath::Clamp(ScreenLoc.X, ViewportMarginX * -1.f, ViewportMarginX);
	ScreenLoc.Y = FMath::Clamp(ScreenLoc.Y, ViewportMarginY * -1.f, ViewportMarginY);
	
	IconCanvasPanelSlot->SetPosition(ScreenLoc);
}

void UMiniWaypoint::SetIconPanelSlot(UCanvasPanel* IconParent, UImage* ArrowImageComp)
{
	ArrowImage = ArrowImageComp;
	IconCanvasPanelSlot = Cast<UCanvasPanelSlot>(IconParent->Slot);
}
