This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/MfGames.Nitride.Temporal.Schedules/ApplySchedules.cs

85 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
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,
Timekeeper timekeeper)
{
this.Timekeeper = timekeeper;
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 timekeeper associated with this operation.
/// </summary>
public Timekeeper Timekeeper { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
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.Timekeeper);
}
return entity;
}
}