// Oleg Petruny proprietary.

#include "InventoryInteractableModificator.h"

#include "EnhancedInputComponent.h"
#include "InputMappingContext.h"

#include "Interactable/Interactable.h"
#include "MainGameModeBase.h"
#include "PlayerBase.h"
#include "Widgets/InteractableHintWidget.h"
#include "Widgets/WidgetsManager.h"

UInventoryInteractableModificator::UInventoryInteractableModificator(const FObjectInitializer& ObjectInitializer)
    : UInteractableModificator(ObjectInitializer)
{
    activatorTypes |= static_cast<uint8>(EActivatorType::Use);

    static ConstructorHelpers::FObjectFinder<UInputMappingContext> asset{ TEXT("/Script/EnhancedInput.InputMappingContext'/Game/Input/Interactables/IMC_InteractableInventory.IMC_InteractableInventory'") };
    inputMapping = asset.Object;
}

void UInventoryInteractableModificator::Bind_Implementation(UEnhancedInputComponent* input)
{
    if(!input)
        return;

    inputMapping.LoadSynchronous();
    if(!inputMapping)
        return;

    auto& mappings = inputMapping->GetMappings();

    auto handle = input->BindAction(mappings[0].Action, ETriggerEvent::Triggered, this, &UInventoryInteractableModificator::TakeAsFirstItem).GetHandle();
    bindindingHandlers.Add(handle);
    handle = input->BindAction(mappings[1].Action, ETriggerEvent::Triggered, this, &UInventoryInteractableModificator::TakeAsSecondItem).GetHandle();
    bindindingHandlers.Add(handle);

    lastInput = input;
    lastPlayer = Cast<APlayerBase>(Cast<APlayerController>(lastInput->GetOwner())->GetPawn());

    AMainGameModeBase::GetWidgetsManager()->ShowInventory(mappings[0].Key.GetDisplayName(false), mappings[1].Key.GetDisplayName(false));
}

void UInventoryInteractableModificator::Unbind_Implementation()
{
    if(!lastInput)
        return;

    for(auto handle : bindindingHandlers)
    {
        lastInput->RemoveBindingByHandle(handle);
    }
    bindindingHandlers.Empty();
}

void UInventoryInteractableModificator::TakeAsFirstItem()
{
    auto actor = GetOwner();

    if(lastPlayer->IsInInventory(actor))
        return;

    lastPlayer->TakeItemToLeftHand(actor);
    if(lastPlayer->leftPocketItem == actor)
        AMainGameModeBase::GetWidgetsManager()->SetInventoryFirstItem(name);
    auto& mappings = inputMapping.LoadSynchronous()->GetMappings();
    AMainGameModeBase::GetWidgetsManager()->ShowInventory(mappings[0].Key.GetDisplayName(false), mappings[1].Key.GetDisplayName(false));
}

void UInventoryInteractableModificator::TakeAsSecondItem()
{
    auto actor = GetOwner();

    if(lastPlayer->IsInInventory(actor))
        return;

    lastPlayer->TakeItemToRightHand(actor);
    if(lastPlayer->rightPocketItem == actor)
        AMainGameModeBase::GetWidgetsManager()->SetInventorySecondItem(name);
    auto& mappings = inputMapping.LoadSynchronous()->GetMappings();
    AMainGameModeBase::GetWidgetsManager()->ShowInventory(mappings[0].Key.GetDisplayName(false), mappings[1].Key.GetDisplayName(false));
}