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


#include "ShelvesStackingController.h"

#include "Faye/Interfaces/InventoryInterface.h"
#include "Faye/Inventory/BookItem.h"
#include "Faye/Inventory/Inventory.h"
#include "Faye/Data/Filters/ItemFilters.h"
#include "GameFramework/Character.h"
#include "Kismet/GameplayStatics.h"
#include "Faye/GameObjects/ShelfActor.h"

UBookItem* UShelvesStackingController::PlaceBookIntoShelf()
{
	FShelvesStackingSetupPayload MutablePayload = Payload.GetMutable<FShelvesStackingSetupPayload>();
	if (!MutablePayload.ShelfActorRef)
	{
		return nullptr;
	}
	
	UInventory* PlayerInventory = IInventoryInterface::Execute_GetInventory(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
	check(PlayerInventory);
	
	UBookFilter* BookFilter = NewObject<UBookFilter>(this);
	BookFilter->BookCategory = SelectedCategory;
	TArray<UItem*> FilteredBooks = PlayerInventory->FilterItems(BookFilter);
	if (FilteredBooks.IsEmpty())
	{
		return nullptr;
	}
	int32 RandIndex = FMath::RandRange(0, FilteredBooks.Num() - 1);
	UBookItem* SelectedBook = Cast<UBookItem>(FilteredBooks[RandIndex]);
	PlayerInventory->RemoveItem(SelectedBook, 1);
	
	UInventory* ShelfInventory = IInventoryInterface::Execute_GetInventory(MutablePayload.ShelfActorRef);
	check(ShelfInventory);
	
	ShelfInventory->AddItem(SelectedBook, 1);
	return SelectedBook;
}
