import 'package:flutter/painting.dart';

import 'original_image_provider.dart';

/// [ImageCache] that uses two caches for small and large images
/// so that a single large image does not evict all small iamges
final class CustomImageCache implements ImageCache {
  final _small = ImageCache();
  final _large = ImageCache();

  @override
  int get maximumSize => _small.maximumSize + _large.maximumSize;

  @override
  int get maximumSizeBytes => _small.maximumSizeBytes + _large.maximumSizeBytes;

  @override
  set maximumSize(int value) => _small.maximumSize = value;

  @override
  set maximumSizeBytes(int value) => _small.maximumSize = value;

  @override
  void clear() {
    _small.clear();
    _large.clear();
  }

  @override
  void clearLiveImages() {
    _small.clearLiveImages();
    _large.clearLiveImages();
  }

  @override
  bool containsKey(Object key) =>
      (key is OriginalImageProvider ? _large : _small).containsKey(key);

  @override
  int get currentSize => _small.currentSize + _large.currentSize;

  @override
  int get currentSizeBytes => _small.currentSizeBytes + _large.currentSizeBytes;

  @override
  bool evict(Object key, {bool includeLive = true}) =>
      (key is OriginalImageProvider ? _large : _small)
          .evict(key, includeLive: includeLive);

  @override
  int get liveImageCount => _small.liveImageCount + _large.liveImageCount;

  @override
  int get pendingImageCount =>
      _small.pendingImageCount + _large.pendingImageCount;

  @override
  ImageStreamCompleter? putIfAbsent(
    Object key,
    ImageStreamCompleter Function() loader, {
    ImageErrorListener? onError,
  }) =>
      (key is OriginalImageProvider ? _large : _small)
          .putIfAbsent(key, loader, onError: onError);

  @override
  ImageCacheStatus statusForKey(Object key) =>
      (key is OriginalImageProvider ? _large : _small).statusForKey(key);
}
