using System;
using System.Collections.Generic;
using System.Linq;
using Gallium;
namespace Nitride.Contents;
///
/// Various extension methods for working with content.
///
public static class EntityContentExtensions
{
///
/// Retrieves the single registered content entity inside the component.
/// If there is more than one, this will throw an exception.
///
/// The entity to query.
/// The one and only content component.
public static IContent GetContent(this Entity entity)
{
Type type = entity.GetComponentTypes().Single(x => typeof(IContent).IsAssignableFrom(x));
return entity.Get(type);
}
///
/// Determines if the entity has at least one content component.
///
/// The entity to inspect.
/// True if there is a component extending `IContent`.
public static bool HasContent(this Entity entity)
{
return entity.GetComponentTypes().Any(x => typeof(IContent).IsAssignableFrom(x));
}
///
/// Remove all existing content components from the entity and then adds
/// the new component into the entity before returning it.
///
/// The entity to query and modify.
/// The content to add to the entity.
/// The base type of the content.
/// The entity or a copy with the new component.
public static Entity SetContent(this Entity entity, TType content)
where TType : IContent
{
IEnumerable? existing = entity.GetComponentTypes().Where(x => typeof(IContent).IsAssignableFrom(x));
foreach (Type? component in existing)
{
entity = entity.Remove(component);
}
return entity.Add(content);
}
}