#include "ZMMOPlayerController.h"

#include "Blueprint/UserWidget.h"
#include "EnhancedInputSubsystems.h"
#include "Engine/LocalPlayer.h"
#include "InputMappingContext.h"
#include "UObject/ConstructorHelpers.h"
#include "Widgets/Input/SVirtualJoystick.h"
#include "ZMMO.h"

AZMMOPlayerController::AZMMOPlayerController()
{
	// Defaults dos Input Mapping Contexts (alinhados ao ZClientMMO). Permitem
	// instanciar AZMMOPlayerController directamente como
	// `PlayerControllerClass` do AZMMOGameMode sem exigir um BP filho. Se o
	// projeto adicionar mais IMCs, podemos extender via BP filho ou via
	// arquivos de Config (UPROPERTY EditAnywhere abaixo).
	static ConstructorHelpers::FObjectFinder<UInputMappingContext> DefaultImc(
		TEXT("/Game/Input/IMC_Default.IMC_Default"));
	static ConstructorHelpers::FObjectFinder<UInputMappingContext> MouseLookImc(
		TEXT("/Game/Input/IMC_MouseLook.IMC_MouseLook"));

	if (DefaultImc.Succeeded())
	{
		DefaultMappingContexts.Add(DefaultImc.Object);
	}
	if (MouseLookImc.Succeeded())
	{
		MobileExcludedMappingContexts.Add(MouseLookImc.Object);
	}
}

void AZMMOPlayerController::BeginPlay()
{
	Super::BeginPlay();

	if (ShouldUseTouchControls() && IsLocalPlayerController())
	{
		MobileControlsWidget = CreateWidget<UUserWidget>(this, MobileControlsWidgetClass);
		if (MobileControlsWidget)
		{
			MobileControlsWidget->AddToPlayerScreen(0);
		}
		else
		{
			UE_LOG(LogZMMO, Error, TEXT("Could not spawn mobile controls widget."));
		}
	}
}

void AZMMOPlayerController::SetupInputComponent()
{
	Super::SetupInputComponent();

	if (!IsLocalPlayerController())
	{
		return;
	}

	if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(GetLocalPlayer()))
	{
		for (UInputMappingContext* CurrentContext : DefaultMappingContexts)
		{
			Subsystem->AddMappingContext(CurrentContext, 0);
		}

		if (!ShouldUseTouchControls())
		{
			for (UInputMappingContext* CurrentContext : MobileExcludedMappingContexts)
			{
				Subsystem->AddMappingContext(CurrentContext, 0);
			}
		}
	}
}

bool AZMMOPlayerController::ShouldUseTouchControls() const
{
	return SVirtualJoystick::ShouldDisplayTouchInterface() || bForceTouchControls;
}
