using Harmonia.Core.Imaging;
using Harmonia.Core.Models;
using Microsoft.Extensions.Caching.Memory;

namespace Harmonia.Core.Caching;

public class AudioImageMemoryCache(IAudioImageExtractor audioImageExtractor) : MemoryCache<Song, SongPictureInfo>, IAudioImageCache
{
    protected override int MaxConcurrentRequests => 8;

    protected override MemoryCacheOptions Options => new()
    {
        SizeLimit = 2000000000,
        CompactionPercentage = 0.2,
    };

    protected override TimeSpan SlidingExpiration => TimeSpan.FromSeconds(600);

    protected override object? GetKey(Song key)
    {
        if (string.IsNullOrWhiteSpace(key.ImageHash) == false)
        {
            return key.ImageHash;
        }
        else if (string.IsNullOrWhiteSpace(key.ImageName) == false)
        {
            return key.ImageName;
        }

        return null;
    }

    protected override async ValueTask<SongPictureInfo?> FetchAsync(Song key, CancellationToken cancellationToken)
    {
        SongPictureInfo? songPictureInfo = await audioImageExtractor.ExtractImageAsync(key.FileName, cancellationToken);

        return songPictureInfo;
    }

    protected override long GetEntrySize(SongPictureInfo entry)
    {
        return entry.Size;
    }
}