package com.lemenzo.gallery.loader;

import android.graphics.Bitmap;
import android.util.LruCache;

/** Process-wide thumbnail cache with a bounded memory budget for very large libraries. */
public final class BitmapMemoryCache {
    private static final int MIN_CACHE_KB = 12 * 1024;
    private static final int MAX_CACHE_KB = 48 * 1024;
    private final LruCache<String, Bitmap> cache;

    public BitmapMemoryCache() {
        long maxMemoryKb = Runtime.getRuntime().maxMemory() / 1024L;
        int targetKb = (int) Math.min(Integer.MAX_VALUE, Math.max(1L, maxMemoryKb / 10L));
        int cacheKb = Math.max(MIN_CACHE_KB, Math.min(MAX_CACHE_KB, targetKb));
        cache = new LruCache<String, Bitmap>(cacheKb) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return Math.max(1, bitmap.getAllocationByteCount() / 1024);
            }
        };
    }

    public Bitmap get(String key) {
        return key == null ? null : cache.get(key);
    }

    public void put(String key, Bitmap bitmap) {
        if (key != null && bitmap != null && cache.get(key) == null) cache.put(key, bitmap);
    }

    public void clear() {
        cache.evictAll();
    }
}
