// Copyright ExByte Studios. Item Interaction Ecosystem.

#include "FuelTankComponent.h"
#include "ItemWorldLog.h"
#include "ItemNativeTags.h"
#include "Net/UnrealNetwork.h"

UFuelTankComponent::UFuelTankComponent()
{
	PrimaryComponentTick.bCanEverTick = false;
	SetIsReplicatedByDefault(true);
}

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

bool UFuelTankComponent::HasAuthority() const
{
	return GetOwner() && GetOwner()->HasAuthority();
}

bool UFuelTankComponent::ReceiveHeldUse(FName ResultVerb, FItemInstanceData& HeldItem, AActor* Instigator)
{
	if (!HasAuthority() || ResultVerb != FName("TransferFuel"))
	{
		return false;
	}

	const float Available = HeldItem.RuntimeProperties.GetFloat(ItemEcosystemTags::Property_FuelAmount, 0.f);
	const float Room = FMath::Max(0.f, MaxFuel - CurrentFuel);
	const float Moved = FMath::Min3(PourAmount, Available, Room);
	if (Moved <= 0.f)
	{
		return false;
	}

	CurrentFuel += Moved;
	HeldItem.RuntimeProperties.SetFloat(ItemEcosystemTags::Property_FuelAmount, Available - Moved);
	OnFuelChanged.Broadcast(CurrentFuel);
	UE_LOG(LogItemWorld, Log, TEXT("[Interaction] poured %.1f fuel (now %.1f/%.1f)"), Moved, CurrentFuel, MaxFuel);
	return true;
}

void UFuelTankComponent::OnRep_Fuel()
{
	OnFuelChanged.Broadcast(CurrentFuel);
}
