// Copyright Pacificao. All Rights Reserved.

#include "AgrarianResourceNode.h"
#include "AgrarianGameCharacter.h"
#include "AgrarianInventoryComponent.h"
#include "AgrarianItemDefinitionAsset.h"
#include "Components/StaticMeshComponent.h"
#include "Net/UnrealNetwork.h"

AAgrarianResourceNode::AAgrarianResourceNode()
{
	bReplicates = true;

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

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

void AAgrarianResourceNode::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);
	DOREPLIFETIME(AAgrarianResourceNode, RemainingHarvests);
}

FText AAgrarianResourceNode::GetInteractionText_Implementation(const AAgrarianGameCharacter* Interactor) const
{
	return RemainingHarvests > 0 ? FText::FromString(TEXT("Gather")) : FText::FromString(TEXT("Depleted"));
}

bool AAgrarianResourceNode::CanInteract_Implementation(const AAgrarianGameCharacter* Interactor) const
{
	return RemainingHarvests > 0 && Interactor != nullptr;
}

void AAgrarianResourceNode::Interact_Implementation(AAgrarianGameCharacter* Interactor)
{
	if (!HasAuthority() || !Interactor || RemainingHarvests <= 0)
	{
		return;
	}

	if (UAgrarianInventoryComponent* Inventory = Interactor->GetInventoryComponent())
	{
		const FAgrarianItemStack Granted = MakeYieldStack();
		if (Inventory->AddItem(Granted))
		{
			RemainingHarvests--;
			UpdateDepletedState();
		}
	}
}

void AAgrarianResourceNode::OnRep_RemainingHarvests()
{
	UpdateDepletedState();
}

FAgrarianItemStack AAgrarianResourceNode::MakeYieldStack() const
{
	if (YieldItemDefinition)
	{
		return YieldItemDefinition->MakeStack(QuantityPerHarvest);
	}

	FAgrarianItemStack Granted = YieldItem;
	Granted.Quantity = QuantityPerHarvest;
	return Granted;
}

void AAgrarianResourceNode::UpdateDepletedState()
{
	if (Mesh)
	{
		Mesh->SetVisibility(RemainingHarvests > 0, true);
		Mesh->SetCollisionEnabled(RemainingHarvests > 0 ? ECollisionEnabled::QueryAndPhysics : ECollisionEnabled::NoCollision);
	}
}
