using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Robust.Shared.Exceptions;
using Robust.Shared.IoC;
using Robust.Shared.ViewVariables;
using Timer = Robust.Shared.Timing.Timer;
namespace Robust.Shared.GameObjects
{
[RegisterComponent, Obsolete("Use a system update loop instead")]
public sealed partial class TimerComponent : Component
{
[Dependency] private readonly IRuntimeLog _runtimeLog = default!;
private readonly List<(Timer timer, CancellationToken source)>
_timers = new();
public int TimerCount => _timers.Count;
///
/// Should this component be removed when no more timers are running?
///
[ViewVariables(VVAccess.ReadWrite)]
public bool RemoveOnEmpty { get; set; } = true;
public void Update(float frameTime)
{
// Manual for loop so we can modify the list while enumerating.
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < _timers.Count; i++)
{
var (timer, cancellationToken) = _timers[i];
if (cancellationToken.IsCancellationRequested)
{
continue;
}
timer.Update(frameTime, _runtimeLog);
}
_timers.RemoveAll(timer => !timer.Item1.IsActive || timer.source.IsCancellationRequested);
}
public void AddTimer(Timer timer, CancellationToken cancellationToken = default)
{
_timers.Add((timer, cancellationToken));
}
///
/// Creates a task that will complete after a given delay.
/// The task is resumed on the main game logic thread.
///
/// The length of time, in milliseconds, to delay for.
///
/// The task that can be awaited.
public Task Delay(int milliseconds, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource