package com.webimageloader.loader;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.WeakHashMap;

import com.webimageloader.util.BitmapUtils;

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

public class PendingRequests {
    private static final String TAG = "PendingRequests";

    private MemoryCache memoryCache;
    private List<Loader> loaders;

    private WeakHashMap<Object, LoaderRequest> pendingsTags;
    private WeakHashMap<LoaderRequest, PendingListeners> pendingsRequests;


    public PendingRequests(MemoryCache memoryCache, List<Loader> loaders) {
        this.memoryCache = memoryCache;
        this.loaders = loaders;

        pendingsTags = new WeakHashMap<Object, LoaderRequest>();
        pendingsRequests = new WeakHashMap<LoaderRequest, PendingListeners>();
    }

    public synchronized Bitmap getBitmap(Object tag, LoaderRequest request) {
        if (memoryCache != null) {
            Bitmap b = memoryCache.get(request);
            if (b != null) {
                // We got this bitmap, cancel old pending work
                cancelPotentialWork(tag);
                return b;
            }
        }

        return null;
    }

    public synchronized Loader.Listener addRequest(Object tag, LoaderRequest request, LoaderManager.Listener listener) {
        if (stillPending(tag, request)) {
            return null;
        }

        cancelPotentialWork(tag);

        pendingsTags.put(tag, request);

        PendingListeners listeners = pendingsRequests.get(request);
        if (listeners == null) {
            listeners = new PendingListeners(tag, listener);
            pendingsRequests.put(request, listeners);

            return new RequestListener(request);
        } else {
            Log.v(TAG, "Reusing request: " + request);
            listeners.add(tag, listener);

            return null;
        }
    }

    protected synchronized void deliverResult(LoaderRequest request, Bitmap b) {
        PendingListeners listeners = pendingsRequests.remove(request);
        if (listeners == null) {
            Log.v(TAG, "Request no longer pending: " + request);
            return;
        }

        saveToMemoryCache(request, b);

        filterTagsForRequest(listeners, request);
        listeners.deliverResult(b);
        pendingsTags.keySet().removeAll(listeners.getTags());
    }

    protected synchronized void deliverError(LoaderRequest request, Throwable t) {
        PendingListeners listeners = pendingsRequests.get(request);
        if (listeners == null) {
            Log.v(TAG, "Request no longer pending: " + request);
            return;
        }

        filterTagsForRequest(listeners, request);
        listeners.deliverError(t);
        pendingsTags.keySet().removeAll(listeners.getTags());
    }

    private void cancelPotentialWork(Object tag) {
        LoaderRequest request = pendingsTags.remove(tag);
        if (request == null) {
            return;
        }

        PendingListeners listeners = pendingsRequests.get(request);
        if (!listeners.remove(tag)) {
            pendingsRequests.remove(request);

            for (Loader loader : loaders) {
                loader.cancel(request);
            }
        }
    }

    /**
     * Remove tags not pending for this request
     */
    private void filterTagsForRequest(PendingListeners listeners, LoaderRequest request) {
        // Tags pending for this request
        Set<Object> tags = listeners.getTags();

        for (Iterator<Object> it = tags.iterator(); it.hasNext(); ) {
            Object tag = it.next();

            // Check if tag is still pending
            if (!stillPending(tag, request)) {
                it.remove();
            }
        }
    }

    private void saveToMemoryCache(LoaderRequest request, Bitmap b) {
        if (memoryCache != null) {
            memoryCache.set(request, b);
        }
    }

    private boolean stillPending(Object tag, LoaderRequest request) {
        return request.equals(pendingsTags.get(tag));
     }

    private class RequestListener implements Loader.Listener {
        private LoaderRequest request;

        public RequestListener(LoaderRequest request) {
            this.request = request;
        }

        @Override
        public void onStreamLoaded(InputStream is) {
            Bitmap b = BitmapUtils.decodeStream(is);
            onBitmapLoaded(b);
        }

        @Override
        public void onBitmapLoaded(Bitmap b) {
            deliverResult(request, b);
        }

        @Override
        public void onError(Throwable t) {
            deliverError(request, t);
        }
    }

    private static class PendingListeners {
        private WeakHashMap<Object, LoaderManager.Listener> listeners;

        public PendingListeners(Object tag, LoaderManager.Listener listener) {
            listeners = new WeakHashMap<Object, LoaderManager.Listener>();

            add(tag, listener);
        }

        public void add(Object tag, LoaderManager.Listener listener) {
            listeners.put(tag, listener);
        }

        /**
         * Remove a listener
         * @return true if this task is still pending
         */
        public boolean remove(Object tag) {
            listeners.remove(tag);

            if (listeners.isEmpty()) {
                return false;
            } else {
                return true;
            }
        }

        public Set<Object> getTags() {
            return listeners.keySet();
        }

        public void deliverResult(Bitmap b) {
            for (LoaderManager.Listener listener : listeners.values()) {
                listener.onLoaded(b);
            }
        }

        public void deliverError(Throwable t) {
            for (LoaderManager.Listener listener : listeners.values()) {
                listener.onError(t);
            }
        }
    }
}

@@ -2053,39 +2053,29 @@
 eners = 
-pendingsRequests.remove
+removeRequest
 (request
@@ -2091,33 +2091,33 @@
   if (listeners 
-=
+!
 = null) %7B%0A      
@@ -2126,61 +2126,40 @@
     
-Log.v(TAG, %22Request no longer pending: %22 + 
+saveToMemoryCache(
 request
+, b
 );%0A
+%0A
     
@@ -2158,38 +2158,58 @@
 );%0A%0A            
-return
+listeners.deliverResult(b)
 ;%0A        %7D%0A%0A   
@@ -2208,78 +2208,123 @@
   %7D%0A
-%0A
     
+%7D%0A%0A
     
-saveToMemoryCache(request, b);%0A%0A        filterTagsForRequest(
+protected synchronized void deliverError(LoaderRequest request, Throwable t) %7B%0A        PendingListeners 
 list
@@ -2320,34 +2320,49 @@
 teners listeners
-, 
+ = removeRequest(
 request);%0A      
@@ -2355,32 +2355,36 @@
 quest);%0A        
+if (
 listeners.delive
@@ -2380,140 +2380,118 @@
 ners
-.deliverResult(b);%0A        pendingsTags.keySet().removeAll(listeners.getTags());%0A    %7D%0A%0A    protected synchronized void deliverError
+ != null) %7B%0A            listeners.deliverError(t);%0A        %7D%0A    %7D%0A%0A    private PendingListeners removeRequest
 (Loa
@@ -2504,37 +2504,24 @@
 uest request
-, Throwable t
 ) %7B%0A        
@@ -2558,35 +2558,38 @@
 endingsRequests.
-get
+remove
 (request);%0A     
@@ -2689,39 +2689,29 @@
         
-    return;%0A    
+%7D else %7B%0A
     
-%7D%0A%0A
         
@@ -2760,39 +2760,8 @@
     
-    listeners.deliverError(t);%0A
     
@@ -2814,24 +2814,61 @@
 getTags());%0A
+        %7D%0A%0A        return listeners;%0A
     %7D%0A%0A    p

Fix error and refactor methods