////////////////////////////////////////////////////////////
//
// LuprexViewportClient.cpp
//
////////////////////////////////////////////////////////////

#include "LuprexViewportClient.h"
#include "Common.h"
#include "PlayerControllerBase.h"
#include "RootCanvas.h"
#include "Engine/GameInstance.h"
#include "Framework/Application/SlateApplication.h"
#include "Layout/WidgetPath.h"
#include "Slate/SObjectWidget.h"

UlxViewportClient::UlxViewportClient(const FObjectInitializer &ObjectInitializer)
	: Super(ObjectInitializer)
{
	UE_LOG(LogLuprexIntegration, Display, TEXT("UlxViewportClient constructed"));
}

bool UlxViewportClient::TryBringToFront(const FWidgetPath &Path)
{
	UGameInstance *GI = GetGameInstance();
	if (!GI) return false;
	AlxPlayerControllerBase *PC = Cast<AlxPlayerControllerBase>(
		GI->GetFirstLocalPlayerController(GetWorld()));
	if (!PC) return false;

	for (int32 Idx = 0; Idx < Path.Widgets.Num(); ++Idx)
	{
		SWidget &SW = Path.Widgets[Idx].Widget.Get();
		if (SW.GetType() != FName(TEXT("SObjectWidget"))) continue;
		UUserWidget *Widget = static_cast<SObjectWidget&>(SW).GetWidgetObject();
		if (Widget && Widget->GetParent() == PC->RootCanvas)
		{
			UlxRootCanvasPanel::BringToFront(Widget);
			return true;
		}
	}
	return false;
}

bool UlxViewportClient::InputKey(const FInputKeyEventArgs &EventArgs)
{
	// Only act on left mouse button presses that bubbled up to the
	// viewport unhandled.  If the click landed on a descendant of a
	// top-level widget in the root canvas, bring that top-level widget
	// to the front.
	if ((EventArgs.Event == IE_Pressed) && (EventArgs.Key == EKeys::LeftMouseButton))
	{
		FSlateApplication &Slate = FSlateApplication::Get();
		FVector2D MousePos = Slate.GetCursorPos();
		FWidgetPath Path = Slate.LocateWindowUnderMouse(
			MousePos, Slate.GetInteractiveTopLevelWindows());
		if (Path.IsValid() && TryBringToFront(Path)) return true;
	}

	return Super::InputKey(EventArgs);
}
