Files
adas-core/adas-core.Domain/Models/PersonResourceAction.cs
2026-06-26 10:29:23 +02:00

59 lines
2.8 KiB
C#

using adas_core.Domain.Enums;
using adas_core.Domain.Utils;
namespace adas_core.Domain.Models;
/// <summary>
/// Represents an action that can be performed on a person resource.
/// </summary>
/// <remarks>
/// Typically used to model operations, commands, or permissions associated with a person entity within a resource-based system.
/// </remarks>
public class PersonResourceAction
{
public ActionsEnum.ResourceAction? Action { get; set; }
public PersonResource? Resource { get; set; }
/// <summary>
/// Applies the specified list of <see cref="PersonResourceAction"/> items and returns the resulting <see cref="PersonResource"/> collection.
/// This overload delegates to another <c>Apply</c> implementation, passing <c>null</c> as the initial state.
/// </summary>
/// <param name="actions">The list of actions to be applied.</param>
/// <returns>A <see cref="List{PersonResource}"/> containing the result of applying the actions.</returns>
public static List<PersonResource>? Apply(List<PersonResourceAction> actions)
{
return Apply(null, actions);
}
/// <summary>
/// Applies a list of add, update, and delete actions to a source list of person resources, returning the resulting list.
/// Resources are added only if not already present, removed when marked for deletion, and replaced in place when updated (or added if not found).
/// </summary>
/// <param name="source">The source list of person resources to mutate. If null, an empty list is used.</param>
/// <param name="actions">The list of resource actions (add, delete, update) to apply to the source. If null, no actions are applied.</param>
/// <returns>The resulting list of person resources after applying the actions, or null if the resulting list is empty.</returns>
public static List<PersonResource>? Apply(List<PersonResource>? source, List<PersonResourceAction>? actions)
{
source ??= [];
(actions ?? []).ForEach(s =>
{
if (s.Resource != null)
switch (s.Action)
{
case ActionsEnum.ResourceAction.Add:
if (!source.Contains(s.Resource)) source.Add(s.Resource);
break;
case ActionsEnum.ResourceAction.Delete:
if (source.Contains(s.Resource)) source.Remove(s.Resource);
break;
case ActionsEnum.ResourceAction.Update:
if (source.Contains(s.Resource)) source[source.IndexOf(s.Resource)] = s.Resource;
else source.Add(s.Resource);
break;
}
});
return CollectionsUtils.NullIfEmpty(source);
}
}