using System.Collections.Concurrent;

namespace BookReader.Services;

/// <summary>
/// Сервис для оптимизированной загрузки изображений с кэшированием ImageSource
/// </summary>
public class CachedImageLoadingService : ICachedImageLoadingService
{
    private readonly ConcurrentDictionary<string, ImageSource> _memoryCache = new();
    private readonly SemaphoreSlim _semaphore = new(3); // Максимум 3 параллельных загрузки

    public async Task<ImageSource?> LoadImageAsync(byte[]? imageData, string cacheKey)
    {
        if (imageData == null || imageData.Length == 0)
            return null;

        // Try memory cache first
        if (_memoryCache.TryGetValue(cacheKey, out var cachedSource))
        {
            return cachedSource;
        }

        // Limit concurrent loads
        await _semaphore.WaitAsync();
        try
        {
            // Double-check after acquiring semaphore
            if (_memoryCache.TryGetValue(cacheKey, out cachedSource))
            {
                return cachedSource;
            }

            // Create new ImageSource
            var imageSource = ImageSource.FromStream(() => new MemoryStream(imageData));
            _memoryCache[cacheKey] = imageSource;

            return imageSource;
        }
        finally
        {
            _semaphore.Release();
        }
    }

    public void ClearCache()
    {
        _memoryCache.Clear();
    }
}
