using Content.Shared.Power.Components;
using JetBrains.Annotations;
namespace Content.Shared.Power.EntitySystems;
///
/// Generic system that handles entities with .
/// Used for simple machines that only need to switch between "idle" and "working" power states.
///
public abstract partial class SharedPowerStateSystem : EntitySystem
{
[Dependency] private SharedPowerReceiverSystem _powerReceiverSystem = default!;
[Dependency] protected EntityQuery PowerStateQuery = default!;
///
/// Sets the working state of the entity, adjusting its power draw accordingly.
///
/// The entity to set the working state for.
/// Whether the entity should be in the working state.
[PublicAPI]
public virtual void SetWorkingState(Entity ent, bool isWorking)
{
if (!PowerStateQuery.Resolve(ent, ref ent.Comp))
return;
SetPowerLoad((ent, ent.Comp), isWorking);
if (ent.Comp.IsWorking == isWorking)
return;
ent.Comp.IsWorking = isWorking;
var ev = new PowerStateChanged(isWorking);
RaiseLocalEvent(ent, ref ev);
}
///
/// Tries to set the working state of the entity, adjusting its power draw accordingly.
/// Use this for if you're not sure if the entity has a .
///
/// The entity to set the working state for.
/// Whether the entity should be in the working state.
[PublicAPI]
public void TrySetWorkingState(Entity ent, bool isWorking)
{
// Sometimes systems calling this API handle generic objects that can or can't consume power,
// so to reduce boilerplate we don't log an error. Any entity that *should* have an ApcPowerRecieverComponent
// will log an error in tests if someone tries to add an entity that doesn't have one.
if (!PowerStateQuery.Resolve(ent, ref ent.Comp, false))
return;
SetWorkingState(ent, isWorking);
}
///
/// Tries to get working state out of ,
/// returns it if found, returns false if not found.
///
[PublicAPI]
public bool GetWorkingState(Entity ent)
{
if (!PowerStateQuery.Resolve(ent, ref ent.Comp))
return false;
return ent.Comp.IsWorking;
}
/// Sets up power load for provided working state.
protected virtual void SetPowerLoad(Entity ent, bool isWorking)
{
SharedApcPowerReceiverComponent? apcPower = null;
if (_powerReceiverSystem.ResolveApc(ent, ref apcPower))
{
var powerLoadToSet = isWorking ? ent.Comp.WorkingPowerDraw : ent.Comp.IdlePowerDraw;
_powerReceiverSystem.SetLoad((ent, apcPower), powerLoadToSet);
}
}
}
///
/// Event of changing power state of entity.
///
[ByRefEvent]
public record struct PowerStateChanged(bool IsWorking);