using SlpModularCms.Core.Media;
using SlpModularCms.Core.Media.Library;
using SlpModularCms.Modules.Hero.Data.Entities;
using SlpModularCms.Modules.Hero.Repositories;
namespace SlpModularCms.Modules.Hero.Services;
///
/// Tells the media library which hero images exist and where they are used (one use per slide, with its position in the
/// hero), and moves them to the trash and back for it. The files are removed by after the trash period.
///
public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageService images) : IMediaUsageProvider
{
public const string SlideKind = "slide";
public string Module => HeroMapping.Area;
public async Task> ListPhotosAsync(CancellationToken cancellationToken)
=> (await repository.GetAllImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
public async Task> ListTrashAsync(CancellationToken cancellationToken)
=> (await repository.GetTrashedImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
public async Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken)
{
var wanted = photoIds.ToHashSet();
var slides = await repository.GetAllSlidesReadOnlyAsync(cancellationToken);
// The position of a slide is its place in its hero, in display order (1-based), also for slides that are off.
var uses = new List();
foreach (var hero in slides.GroupBy(s => s.HeroId))
{
var ordered = hero.OrderBy(s => s.SortOrder).ThenBy(s => s.Id).ToList();
for (var index = 0; index < ordered.Count; index++)
{
var slide = ordered[index];
if (wanted.Contains(slide.ImageId))
{
uses.Add(new MediaUse(Module, slide.ImageId, SlideKind, index + 1, slide.IsActive));
}
}
}
return uses;
}
public async Task TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
{
try
{
return await images.TrashAsync(photoId, callerId, cancellationToken);
}
catch (HeroImageNotFoundException)
{
return null;
}
}
public Task RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
=> images.RestoreAsync(photoId, callerId, cancellationToken);
private MediaPhoto ToPhoto(HeroImage i)
=> new(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i), i.OriginalFileName, i.LastUsedAt, i.DeletedAt);
/// The smallest published WebP of the set; null while the set is not cut yet.
private static string? Thumbnail(HeroImage image)
{
var pick = HeroMapping.Published(image).Where(v => v.Type == ImageFormat.WebP.MimeType()).OrderBy(v => v.Width).FirstOrDefault();
return pick is null || string.IsNullOrEmpty(image.SetHash) ? null : MediaPaths.Url(HeroMapping.Area, image.SetHash, pick.FileName);
}
}