#include "LuprexUserWidget.h"
#include "EnhancedInputComponent.h"
#include "InputAction.h"

UlxUserWidget::UlxUserWidget(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
}

void UlxUserWidget::NativeOnInitialized()
{
	Super::NativeOnInitialized();
	BackupInputComponent();
}

void UlxUserWidget::BackupInputComponent()
{
	SavedEnhancedActionEventBindings.Reset();

	UEnhancedInputComponent* EIC = Cast<UEnhancedInputComponent>(InputComponent);
	if (!EIC) return;

	const TArray<EventBinding>& Live = EIC->GetActionEventBindings();
	SavedEnhancedActionEventBindings.Reserve(Live.Num());
	for (const EventBinding& Binding : Live)
	{
		SavedEnhancedActionEventBindings.Add(Binding->Clone());
	}
}

void UlxUserWidget::DisableInputAction(const UInputAction* InputAction)
{
	UEnhancedInputComponent* EIC = Cast<UEnhancedInputComponent>(InputComponent);
	if (!EIC) return;

	TArray<EventBinding>& Bindings = GetMutableActionEventBindings(EIC);
	Bindings.RemoveAll([InputAction](const EventBinding& B)
	{
		return B->GetAction() == InputAction;
	});
}

void UlxUserWidget::RestoreInputAction(const UInputAction* InputAction)
{
	DisableInputAction(InputAction);

	UEnhancedInputComponent* EIC = Cast<UEnhancedInputComponent>(InputComponent);
	if (!EIC) return;

	TArray<EventBinding>& Live = GetMutableActionEventBindings(EIC);
	for (const EventBinding& Saved : SavedEnhancedActionEventBindings)
	{
		if (Saved->GetAction() == InputAction)
		{
			Live.Add(Saved->Clone());
		}
	}
}

void UlxUserWidget::RedirectInputAction(const UInputAction* From, const UInputAction* To)
{
	DisableInputAction(From);

	UEnhancedInputComponent* EIC = Cast<UEnhancedInputComponent>(InputComponent);
	if (!EIC) return;

	for (const EventBinding& Saved : SavedEnhancedActionEventBindings)
	{
		if (Saved->GetAction() == To)
		{
			TSharedPtr<FEnhancedInputActionEventBinding> Clone(Saved->Clone().Release());
			EIC->BindActionInstanceLambda(From, Saved->GetTriggerEvent(),
				[Clone](const FInputActionInstance& Data)
				{
					Clone->Execute(Data);
				});
		}
	}
}

TArray<UlxUserWidget::EventBinding>& UlxUserWidget::GetMutableActionEventBindings(UEnhancedInputComponent* EIC)
{
	return const_cast<TArray<EventBinding>&>(EIC->GetActionEventBindings());
}
