// Copyright Pacificao. All Rights Reserved.

#include "AgrarianItemPickup.h"
#include "AgrarianGameCharacter.h"
#include "AgrarianInventoryComponent.h"
#include "AgrarianItemDefinitionAsset.h"
#include "Components/StaticMeshComponent.h"

AAgrarianItemPickup::AAgrarianItemPickup()
{
	bReplicates = true;
	NetCullDistanceSquared = FMath::Square(3000.0f);

	Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
	RootComponent = Mesh;
	Mesh->SetCollisionProfileName(TEXT("BlockAll"));

	PickupStack.ItemId = TEXT("wood");
	PickupStack.DisplayName = FText::FromString(TEXT("Wood"));
	PickupStack.Quantity = 1;
	PickupStack.UnitWeight = 1.0f;
	InteractionVerb = FText::FromString(TEXT("Pick up"));
}

FText AAgrarianItemPickup::GetInteractionText_Implementation(const AAgrarianGameCharacter* Interactor) const
{
	const FAgrarianItemStack Stack = MakePickupStack();
	const FText DisplayName = Stack.DisplayName.IsEmpty() ? FText::FromName(Stack.ItemId) : Stack.DisplayName;
	const FString Verb = InteractionVerb.IsEmpty() ? FString(TEXT("Pick up")) : InteractionVerb.ToString();

	if (Stack.Quantity > 1)
	{
		return FText::FromString(FString::Printf(TEXT("%s %s x%d"), *Verb, *DisplayName.ToString(), Stack.Quantity));
	}

	return FText::FromString(FString::Printf(TEXT("%s %s"), *Verb, *DisplayName.ToString()));
}

bool AAgrarianItemPickup::CanInteract_Implementation(const AAgrarianGameCharacter* Interactor) const
{
	return Interactor != nullptr && MakePickupStack().IsValidStack();
}

void AAgrarianItemPickup::Interact_Implementation(AAgrarianGameCharacter* Interactor)
{
	if (!HasAuthority() || !Interactor)
	{
		return;
	}

	UAgrarianInventoryComponent* Inventory = Interactor->GetInventoryComponent();
	if (!Inventory)
	{
		return;
	}

	const FAgrarianItemStack Stack = MakePickupStack();
	if (Inventory->AddItem(Stack))
	{
		Destroy();
	}
}

FAgrarianItemStack AAgrarianItemPickup::MakePickupStack() const
{
	if (ItemDefinition)
	{
		return ItemDefinition->MakeStack(Quantity);
	}

	FAgrarianItemStack Stack = PickupStack;
	if (Quantity > 0)
	{
		Stack.Quantity = Quantity;
	}
	return Stack;
}
