package com.github.kubatatami.judonetworking.callbacks;

import android.view.View;

import com.github.kubatatami.judonetworking.AsyncResult;
import com.github.kubatatami.judonetworking.CacheInfo;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * Created by Kuba on 23/05/14.
 */
public class ViewAdapterCallback<Z, T> extends DefaultCallback<T> {

    protected static final Map<View, ViewAdapterCallback> viewCache = new WeakHashMap<>();

    protected final View view;

    protected AsyncResult asyncResult;

    protected Z object;

    public ViewAdapterCallback(View view) {
        this.view = view;
    }

    public void setObject(Z object) {
        this.object = object;
        cancelRequest(view);
        viewCache.put(view, this);
    }

    @Override
    public void onStart(CacheInfo cacheInfo, AsyncResult asyncResult) {
        super.onStart(cacheInfo, asyncResult);
        this.asyncResult = asyncResult;
        if (viewCache.get(view) != this) {
            asyncResult.cancel();
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
        if (viewCache.containsKey(view) && viewCache.get(view) == this) {
            viewCache.remove(view);
        }
    }


    public static void cancelRequest(View view) {
        if (viewCache.containsKey(view)) {
            if (viewCache.get(view).asyncResult != null) {
                viewCache.get(view).asyncResult.cancel();
            }
            viewCache.remove(view);
        }
    }

}

@@ -520,33 +520,8 @@
 t;%0A%0A
-    protected Z object;%0A%0A
     
@@ -597,147 +597,8 @@
  %7D%0A%0A
-    public void setObject(Z object) %7B%0A        this.object = object;%0A        cancelRequest(view);%0A        viewCache.put(view, this);%0A    %7D%0A%0A
     
@@ -774,39 +774,117 @@
         
-if (viewCache.get(view)
+ViewAdapterCallback oldCallback = viewCache.get(view);%0A        if (oldCallback != null && oldCallback
  != this
@@ -899,17 +899,32 @@
         
-a
+oldCallback.getA
 syncResu
@@ -917,32 +917,34 @@
 k.getAsyncResult
+()
 .cancel();%0A     
@@ -944,24 +944,59 @@
 ;%0A        %7D%0A
+        viewCache.put(view, this);%0A
     %7D%0A%0A    @

improve ViewAdapterCallback