using System;
using System.Linq;
using Content.Server.GameObjects.Components.Sound;
using Content.Server.GameObjects.EntitySystems;
using Content.Server.GameObjects.Components.Power;
using Content.Server.Interfaces;
using Content.Server.Interfaces.GameObjects;
using Content.Server.Utility;
using Content.Shared.Chemistry;
using Content.Shared.GameObjects.Components.Chemistry;
using Content.Shared.GameObjects.EntitySystems;
using Robust.Server.GameObjects.Components.Container;
using Robust.Server.GameObjects.Components.UserInterface;
using Robust.Server.Interfaces.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Shared.GameObjects.Systems;
namespace Content.Server.GameObjects.Components.Chemistry
{
///
/// Contains all the server-side logic for reagent dispensers. See also .
/// This includes initializing the component based on prototype data, and sending and receiving messages from the client.
/// Messages sent to the client are used to update update the user interface for a component instance.
/// Messages sent from the client are used to handle ui button presses.
///
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(IInteractUsing))]
public class ReagentDispenserComponent : SharedReagentDispenserComponent, IActivate, IInteractUsing, ISolutionChange
{
#pragma warning disable 649
[Dependency] private readonly IServerNotifyManager _notifyManager;
[Dependency] private readonly ILocalizationManager _localizationManager;
#pragma warning restore 649
[ViewVariables] private BoundUserInterface _userInterface;
[ViewVariables] private ContainerSlot _beakerContainer;
[ViewVariables] private string _packPrototypeId;
[ViewVariables] private bool HasBeaker => _beakerContainer.ContainedEntity != null;
[ViewVariables] private ReagentUnit _dispenseAmount = ReagentUnit.New(10);
[ViewVariables]
private SolutionComponent Solution => _beakerContainer.ContainedEntity.GetComponent();
///implementing PowerDeviceComponent
private PowerDeviceComponent _powerDevice;
private bool Powered => _powerDevice.Powered;
///
/// Shows the serializer how to save/load this components yaml prototype.
///
/// Yaml serializer
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _packPrototypeId, "pack", string.Empty);
}
///
/// Called once per instance of this component. Gets references to any other components needed
/// by this component and initializes it's UI and other data.
///
public override void Initialize()
{
base.Initialize();
_userInterface = Owner.GetComponent()
.GetBoundUserInterface(ReagentDispenserUiKey.Key);
_userInterface.OnReceiveMessage += OnUiReceiveMessage;
_beakerContainer =
ContainerManagerComponent.Ensure($"{Name}-reagentContainerContainer", Owner);
_powerDevice = Owner.GetComponent();
InitializeFromPrototype();
UpdateUserInterface();
}
///
/// Checks to see if the pack defined in this components yaml prototype
/// exists. If so, it fills the reagent inventory list.
///
private void InitializeFromPrototype()
{
if (string.IsNullOrEmpty(_packPrototypeId)) return;
var prototypeManager = IoCManager.Resolve();
if (!prototypeManager.TryIndex(_packPrototypeId, out ReagentDispenserInventoryPrototype packPrototype))
{
return;
}
foreach (var entry in packPrototype.Inventory)
{
Inventory.Add(new ReagentDispenserInventoryEntry(entry));
}
}
///
/// Handles ui messages from the client. For things such as button presses
/// which interact with the world and require server action.
///
/// A user interface message from the client.
private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj)
{
if(!PlayerCanUseDispenser(obj.Session.AttachedEntity))
return;
var msg = (UiButtonPressedMessage) obj.Message;
switch (msg.Button)
{
case UiButton.Eject:
TryEject(obj.Session.AttachedEntity);
break;
case UiButton.Clear:
TryClear();
break;
case UiButton.SetDispenseAmount1:
_dispenseAmount = ReagentUnit.New(1);
break;
case UiButton.SetDispenseAmount5:
_dispenseAmount = ReagentUnit.New(5);
break;
case UiButton.SetDispenseAmount10:
_dispenseAmount = ReagentUnit.New(10);
break;
case UiButton.SetDispenseAmount25:
_dispenseAmount = ReagentUnit.New(25);
break;
case UiButton.SetDispenseAmount50:
_dispenseAmount = ReagentUnit.New(50);
break;
case UiButton.SetDispenseAmount100:
_dispenseAmount = ReagentUnit.New(100);
break;
case UiButton.Dispense:
if (HasBeaker)
{
TryDispense(msg.DispenseIndex);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
ClickSound();
}
///
/// Checks whether the player entity is able to use the chem dispenser.
///
/// The player entity.
/// Returns true if the entity can use the dispenser, and false if it cannot.
private bool PlayerCanUseDispenser(IEntity playerEntity)
{
//Need player entity to check if they are still able to use the dispenser
if (playerEntity == null)
return false;
//Check if player can interact in their current state
if (!ActionBlockerSystem.CanInteract(playerEntity) || !ActionBlockerSystem.CanUse(playerEntity))
return false;
//Check if device is powered
if (!Powered)
return false;
return true;
}
///
/// Gets component data to be used to update the user interface client-side.
///
/// Returns a
private ReagentDispenserBoundUserInterfaceState GetUserInterfaceState()
{
var beaker = _beakerContainer.ContainedEntity;
if (beaker == null)
{
return new ReagentDispenserBoundUserInterfaceState(false, ReagentUnit.New(0), ReagentUnit.New(0),
"", Inventory, Owner.Name, null, _dispenseAmount);
}
var solution = beaker.GetComponent();
return new ReagentDispenserBoundUserInterfaceState(true, solution.CurrentVolume, solution.MaxVolume,
beaker.Name, Inventory, Owner.Name, solution.ReagentList.ToList(), _dispenseAmount);
}
private void UpdateUserInterface()
{
var state = GetUserInterfaceState();
_userInterface.SetState(state);
}
///
/// If this component contains an entity with a , eject it.
/// Tries to eject into user's hands first, then ejects onto dispenser if both hands are full.
///
private void TryEject(IEntity user)
{
if (!HasBeaker)
return;
var beaker = _beakerContainer.ContainedEntity;
_beakerContainer.Remove(_beakerContainer.ContainedEntity);
UpdateUserInterface();
if(!user.TryGetComponent(out var hands) || !beaker.TryGetComponent(out var item))
return;
if (hands.CanPutInHand(item))
hands.PutInHand(item);
}
///
/// If this component contains an entity with a , remove all of it's reagents / solutions.
///
private void TryClear()
{
if (!HasBeaker) return;
var solution = _beakerContainer.ContainedEntity.GetComponent();
solution.RemoveAllSolution();
UpdateUserInterface();
}
///
/// If this component contains an entity with a , attempt to dispense the specified reagent to it.
///
/// The index of the reagent in Inventory.
private void TryDispense(int dispenseIndex)
{
if (!HasBeaker) return;
var solution = _beakerContainer.ContainedEntity.GetComponent();
solution.TryAddReagent(Inventory[dispenseIndex].ID, _dispenseAmount, out _);
UpdateUserInterface();
}
///
/// Called when you click the owner entity with an empty hand. Opens the UI client-side if possible.
///
/// Data relevant to the event such as the actor which triggered it.
void IActivate.Activate(ActivateEventArgs args)
{
if (!args.User.TryGetComponent(out IActorComponent actor))
{
return;
}
if (!args.User.TryGetComponent(out IHandsComponent hands))
{
_notifyManager.PopupMessage(Owner.Transform.GridPosition, args.User,
_localizationManager.GetString("You have no hands."));
return;
}
if (!Powered)
return;
var activeHandEntity = hands.GetActiveHand?.Owner;
if (activeHandEntity == null)
{
_userInterface.Open(actor.playerSession);
}
}
///
/// Called when you click the owner entity with something in your active hand. If the entity in your hand
/// contains a , if you have hands, and if the dispenser doesn't already
/// hold a container, it will be added to the dispenser.
///
/// Data relevant to the event such as the actor which triggered it.
///
bool IInteractUsing.InteractUsing(InteractUsingEventArgs args)
{
if (!args.User.TryGetComponent(out IHandsComponent hands))
{
_notifyManager.PopupMessage(Owner.Transform.GridPosition, args.User,
_localizationManager.GetString("You have no hands."));
return true;
}
var activeHandEntity = hands.GetActiveHand.Owner;
if (activeHandEntity.TryGetComponent(out var solution))
{
if (HasBeaker)
{
_notifyManager.PopupMessage(Owner.Transform.GridPosition, args.User,
_localizationManager.GetString("This dispenser already has a container in it."));
}
else if ((solution.Capabilities & SolutionCaps.FitsInDispenser) == 0)
{
//If it can't fit in the dispenser, don't put it in. For example, buckets and mop buckets can't fit.
_notifyManager.PopupMessage(Owner.Transform.GridPosition, args.User,
_localizationManager.GetString("That can't fit in the dispenser."));
}
else
{
_beakerContainer.Insert(activeHandEntity);
UpdateUserInterface();
}
}
else
{
_notifyManager.PopupMessage(Owner.Transform.GridPosition, args.User,
_localizationManager.GetString("You can't put this in the dispenser."));
}
return true;
}
void ISolutionChange.SolutionChanged(SolutionChangeEventArgs eventArgs) => UpdateUserInterface();
private void ClickSound()
{
EntitySystem.Get().PlayFromEntity("/Audio/machines/machine_switch.ogg", Owner, AudioParams.Default.WithVolume(-2f));
}
}
}