Files
tbd-station-14/Content.Server/GameObjects/Components/Items/Storage/StorageCounterComponent.cs
mirrorcult 1c7285825c Refactor ExtinguisherCabinet->ItemCabinet and actually maps them in, adds EntityWhitelist (#4154)
* i probably shouldnt have done this in one commit

* map nonsense

* fix example code

* unnecessary

* test

* reviews

* little fix for open datafield

* add soul
2021-06-09 12:10:29 +10:00

89 lines
2.8 KiB
C#

#nullable enable
using System.Collections.Generic;
using Content.Shared.GameObjects.Components;
using Content.Shared.GameObjects.Components.Tag;
using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.Log;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager.Attributes;
namespace Content.Server.GameObjects.Components.Items.Storage
{
/// <summary>
/// Storage that spawns and counts a single item.
/// Usually used for things like matchboxes, cigarette packs,
/// cigar cases etc.
/// </summary>
/// <code>
/// - type: StorageCounter
/// amount: 6 # Note: this field can be omitted
/// countTag: Cigarette # Note: field doesn't point to entity Id, but its tag
/// </code>
[RegisterComponent]
public class StorageCounterComponent : Component, ISerializationHooks
{
// TODO Convert to EntityWhitelist
[DataField("countTag")]
private string? _countTag;
[DataField("amount")]
private int? _maxAmount;
/// <summary>
/// Single item storage component usually have an attached StackedVisualizer.
/// </summary>
[ComponentDependency] private readonly AppearanceComponent? _appearanceComponent = default;
public override string Name => "StorageCounter";
void ISerializationHooks.AfterDeserialization()
{
if (_countTag == null)
{
Logger.Warning("StorageCounterComponent without a `countTag` is useless");
}
}
public override void HandleMessage(ComponentMessage message, IComponent? component)
{
base.HandleMessage(message, component);
if (_appearanceComponent != null)
{
switch (message)
{
case ContainerContentsModifiedMessage msg:
var actual = Count(msg.Container.ContainedEntities);
_appearanceComponent.SetData(StackVisuals.Actual, actual);
if (_maxAmount != null)
{
_appearanceComponent.SetData(StackVisuals.MaxCount, _maxAmount);
}
break;
}
}
}
private int Count(IReadOnlyList<IEntity> containerContainedEntities)
{
var count = 0;
if (_countTag != null)
{
foreach (var entity in containerContainedEntities)
{
if (entity.HasTag(_countTag))
{
count++;
}
}
}
return count;
}
}
}