88 lines
2.2 KiB
C#
88 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
|
|
using FluentValidation;
|
|
|
|
using MfGames.Gallium;
|
|
using MfGames.Nitride.Generators;
|
|
|
|
namespace MfGames.Nitride.Temporal.Schedules;
|
|
|
|
/// <summary>
|
|
/// Applies schedules against the list of entities.
|
|
/// </summary>
|
|
[WithProperties]
|
|
public partial class ApplySchedules : OperationBase
|
|
{
|
|
private readonly IValidator<ApplySchedules> validator;
|
|
|
|
public ApplySchedules(
|
|
IValidator<ApplySchedules> validator,
|
|
TimeService timeService)
|
|
{
|
|
this.TimeService = timeService;
|
|
this.validator = validator;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets or sets the callback to get the schedules for the entity. This is
|
|
/// used to allow for per-entity schedules or generic schedules across
|
|
/// the entire system. If this returns null, then no schedule will be
|
|
/// applied.
|
|
/// </summary>
|
|
public Func<Entity, IList<ISchedule>?>? GetSchedules { get; set; }
|
|
|
|
/// <summary>
|
|
/// Gets or sets the time service associated with this operation.
|
|
/// </summary>
|
|
public TimeService TimeService { get; set; }
|
|
|
|
/// <inheritdoc />
|
|
public override IEnumerable<Entity> Run(
|
|
IEnumerable<Entity> input,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
this.validator.ValidateAndThrow(this);
|
|
|
|
return input.Select(this.Apply);
|
|
}
|
|
|
|
public ApplySchedules WithGetSchedules<TType>(
|
|
Func<Entity, IEnumerable<TType>?> value)
|
|
where TType : ISchedule
|
|
{
|
|
this.GetSchedules = entity => value?
|
|
.Invoke(entity)
|
|
?.Cast<ISchedule>()
|
|
.ToList();
|
|
|
|
return this;
|
|
}
|
|
|
|
private Entity Apply(Entity entity)
|
|
{
|
|
// Get the schedule for this entity.
|
|
IList<ISchedule>? schedules = this.GetSchedules?.Invoke(entity);
|
|
|
|
if (schedules == null || schedules.Count == 0)
|
|
{
|
|
return entity;
|
|
}
|
|
|
|
// Otherwise, apply the schedules to this entity.
|
|
foreach (ISchedule schedule in schedules)
|
|
{
|
|
if (!schedule.CanApply(entity))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
entity = schedule.Apply(entity, this.TimeService);
|
|
}
|
|
|
|
return entity;
|
|
}
|
|
}
|