using Content.Shared.Containers.ItemSlots;
using Content.Shared.Interaction;
using Content.Shared.Nutrition.Components;
using Content.Shared.Nutrition.EntitySystems;
using Robust.Shared.Containers;
using System.Diagnostics.CodeAnalysis;
namespace Content.Shared.Cabinet;
///
/// Controls ItemCabinet slot locking and visuals.
///
public sealed class ItemCabinetSystem : EntitySystem
{
[Dependency] private readonly ItemSlotsSystem _slots = default!;
[Dependency] private readonly OpenableSystem _openable = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
///
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent(OnStartup);
SubscribeLocalEvent(OnMapInit);
SubscribeLocalEvent(OnContainerModified);
SubscribeLocalEvent(OnContainerModified);
SubscribeLocalEvent(OnOpened);
SubscribeLocalEvent(OnClosed);
}
private void OnStartup(Entity ent, ref ComponentStartup args)
{
UpdateAppearance(ent);
}
private void OnMapInit(Entity ent, ref MapInitEvent args)
{
// update at mapinit to avoid copy pasting locked: true and locked: false for each closed/open prototype
SetSlotLock(ent, !_openable.IsOpen(ent));
}
private void UpdateAppearance(Entity ent)
{
_appearance.SetData(ent, ItemCabinetVisuals.ContainsItem, HasItem(ent));
}
private void OnContainerModified(EntityUid uid, ItemCabinetComponent component, ContainerModifiedMessage args)
{
if (args.Container.ID == component.Slot)
UpdateAppearance((uid, component));
}
private void OnOpened(Entity ent, ref OpenableOpenedEvent args)
{
SetSlotLock(ent, false);
}
private void OnClosed(Entity ent, ref OpenableClosedEvent args)
{
SetSlotLock(ent, true);
}
///
/// Tries to get the cabinet's item slot.
///
public bool TryGetSlot(Entity ent, [NotNullWhen(true)] out ItemSlot? slot)
{
slot = null;
if (!TryComp(ent, out var slots))
return false;
return _slots.TryGetSlot(ent, ent.Comp.Slot, out slot, slots);
}
///
/// Returns true if the cabinet contains an item.
///
public bool HasItem(Entity ent)
{
return TryGetSlot(ent, out var slot) && slot.HasItem;
}
///
/// Lock or unlock the underlying item slot.
///
public void SetSlotLock(Entity ent, bool closed)
{
if (!TryComp(ent, out var slots))
return;
if (_slots.TryGetSlot(ent, ent.Comp.Slot, out var slot, slots))
_slots.SetLock(ent, slot, closed, slots);
}
}