package com.webimageloader.loader;

import com.webimageloader.ImageLoader.Logger;
import com.webimageloader.util.Android;
import com.webimageloader.util.LruCache;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.util.Log;

import java.util.WeakHashMap;

public class MemoryCache {
    private static final String TAG = "MemoryLoader";

    public static class Entry {
        public final Bitmap bitmap;
        public final Metadata metadata;

        private Entry(Bitmap bitmap, Metadata metadata) {
            this.bitmap = bitmap;
            this.metadata = metadata;
        }
    }

    public static class DebugInfo {
        public final int hitCount;
        public final int missCount;
        public final int putCount;
        public final int evictionCount;
        public final int numImages;

        private DebugInfo(int hitCount, int missCount, int putCount, int evictionCount, int numImages) {
            this.hitCount = hitCount;
            this.missCount = missCount;
            this.putCount = putCount;
            this.evictionCount = evictionCount;
            this.numImages = numImages;
        }
    }

    private LruCache<String, Entry> cache;
    private WeakHashMap<String, Entry> expired;

    public MemoryCache(int maxSize) {
        cache = new BitmapCache(maxSize);
        expired = new WeakHashMap<String, Entry>();
    }

    public int size() {
        return cache.size();
    }

    public int maxSize() {
        return cache.maxSize();
    }

    public void trimToSize(int maxSize) {
        cache.trimToSize(maxSize);
    }

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

    public Entry get(LoaderRequest request) {
        String cacheKey = request.getCacheKey();
        Entry entry = cache.get(cacheKey);
        if (entry != null) {
            if (Logger.VERBOSE) Log.v(TAG, "Loaded " + request + " from memory");
        } else {
            entry = expired.remove(cacheKey);
            if (entry != null) {
                cache.put(cacheKey, entry);
                if (Logger.VERBOSE) Log.v(TAG, "Loaded " + request + " from expired memory");
            }
        }

        return entry;
    }

    public void put(LoaderRequest request, Bitmap b, Metadata metadata) {
        // Add the bitmap to the cache if we can fit at least six images of this size,
        // this way we avoid caching large images that will evict all other entries
        if (sizeOf(b) < cache.maxSize() / 6) {
            cache.put(request.getCacheKey(), new Entry(b, metadata));
        }
    }

    public void updateMetadata(LoaderRequest request, Metadata metadata) {
        String cacheKey = request.getCacheKey();
        Entry entry = cache.get(cacheKey);
        if (entry != null) {
            cache.put(cacheKey, new Entry(entry.bitmap, metadata));
        }
    }

    public DebugInfo getDebugInfo() {
        return new DebugInfo(cache.hitCount(), cache.missCount(), cache.putCount(), cache.evictionCount(), cache.snapshot().size());
    }

    @TargetApi(12)
    private static int sizeOf(Bitmap b) {
        if (Android.isAPI(12)) {
            return b.getByteCount();
        } else {
            return b.getRowBytes() * b.getHeight();
        }
    }

    private class BitmapCache extends LruCache<String, Entry> {
        public BitmapCache(int maxSize) {
            super(maxSize);
        }

        @Override
        protected int sizeOf(String key, Entry value) {
            Bitmap b = value.bitmap;

            return MemoryCache.sizeOf(b);
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, Entry oldValue, Entry newValue) {
            if (evicted) {
                expired.put(key, oldValue);
            }
        }
    }
}

@@ -252,16 +252,130 @@
 l.Log;%0A%0A
+import java.lang.ref.WeakReference;%0Aimport java.util.Collections;%0Aimport java.util.HashMap;%0Aimport java.util.Map;%0A
 import j
@@ -396,16 +396,16 @@
 ashMap;%0A
-
 %0Apublic 
@@ -727,32 +727,560 @@
        %7D%0A    %7D%0A%0A
+    private static class WeakEntry %7B%0A        public final WeakReference%3CBitmap%3E reference;%0A        public final Metadata metadata;%0A%0A        private WeakEntry(Entry entry) %7B%0A            this.reference = new WeakReference%3CBitmap%3E(entry.bitmap);%0A            this.metadata = entry.metadata;%0A        %7D%0A%0A        public Entry toEntry() %7B%0A            Bitmap b = reference.get();%0A            if (b == null) %7B%0A                return null;%0A            %7D else %7B%0A                return new Entry(b, metadata);%0A            %7D%0A        %7D%0A    %7D%0A%0A
     public stati
@@ -1863,24 +1863,16 @@
 private 
-WeakHash
 Map%3CStri
@@ -1871,24 +1871,28 @@
 Map%3CString, 
+Weak
 Entry%3E expir
@@ -1994,24 +1994,48 @@
 pired = 
+Collections.synchronizedMap(
 new 
-Weak
 HashMap%3C
@@ -2046,16 +2046,20 @@
 ng, 
+Weak
 Entry%3E()
 ;%0A  
@@ -2054,16 +2054,17 @@
 Entry%3E()
+)
 ;%0A    %7D%0A
@@ -2614,17 +2614,31 @@
         
-e
+WeakEntry weakE
 ntry = e
@@ -2670,37 +2670,82 @@
             if (
-entry
+weakEntry != null && (entry = weakEntry.toEntry())
  != null) %7B%0A    
@@ -4474,16 +4474,30 @@
 ut(key, 
+new WeakEntry(
 oldValue
@@ -4497,16 +4497,17 @@
 ldValue)
+)
 ;%0A      

Handle expired memory properly