package fr.free.nrw.commons;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.Toast;

import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;

import javax.inject.Inject;

import fr.free.nrw.commons.mwapi.MediaWikiApi;
import timber.log.Timber;

public class MediaWikiImageView extends SimpleDraweeView {
    @Inject MediaWikiApi mwApi;
    @Inject LruCache<String, String> thumbnailUrlCache;

    private ThumbnailFetchTask currentThumbnailTask;

    public MediaWikiImageView(Context context) {
        this(context, null);
        init();
    }

    public MediaWikiImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init();
    }

    public MediaWikiImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void setMedia(Media media) {
        if (currentThumbnailTask != null) {
            currentThumbnailTask.cancel(true);
        }
        if (media == null) {
            return;
        }

        if (thumbnailUrlCache.get(media.getFilename()) != null) {
            setImageUrl(thumbnailUrlCache.get(media.getFilename()));
        } else {
            setImageUrl(null);
            currentThumbnailTask = new ThumbnailFetchTask(media, mwApi);
            currentThumbnailTask.execute(media.getFilename());
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        if (currentThumbnailTask != null) {
            currentThumbnailTask.cancel(true);
        }
        super.onDetachedFromWindow();
    }

    private void init() {
        ((CommonsApplication) getContext().getApplicationContext()).injector().inject(this);
        setHierarchy(GenericDraweeHierarchyBuilder
                .newInstance(getResources())
                .setPlaceholderImage(VectorDrawableCompat.create(getResources(),
                        R.drawable.ic_image_black_24dp, getContext().getTheme()))
                .setFailureImage(VectorDrawableCompat.create(getResources(),
                        R.drawable.ic_image_black_24dp, getContext().getTheme()))
                .build());
    }

    private void setImageUrl(@Nullable String url) {
        setImageURI(url);
    }

    private class ThumbnailFetchTask extends MediaThumbnailFetchTask {
        ThumbnailFetchTask(@NonNull Media media, @NonNull MediaWikiApi mwApi) {
            super(media, mwApi);
        }

        @Override
        protected void onPostExecute(String result) {
            if (isCancelled()) {
                return;
            }
            if (TextUtils.isEmpty(result) && media.getLocalUri() != null) {
                result = media.getLocalUri().toString();
            } else {
                // only cache meaningful thumbnails received from network.
                try {
                    thumbnailUrlCache.put(media.getFilename(), result);
                } catch (NullPointerException npe) {
                    Timber.e("error when adding pic to cache " + npe);

                    Toast.makeText(getContext(), R.string.error_while_cache, Toast.LENGTH_SHORT).show();
                }
            }
            setImageUrl(result);
        }
    }
}

@@ -1128,32 +1128,141 @@
  init();%0A    %7D%0A%0A
+    /**%0A     * Sets the media. Fetches its thumbnail if necessary.%0A     * @param media the new media%0A     */%0A
     public void 
@@ -1281,24 +1281,24 @@
 ia media) %7B%0A
-
         if (
@@ -1978,32 +1978,87 @@
 indow();%0A    %7D%0A%0A
+    /**%0A     * Initializes MediaWikiImageView.%0A     */%0A
     private void
@@ -2604,32 +2604,127 @@
 uild());%0A    %7D%0A%0A
+    /**%0A     * Displays the image from the URL.%0A     * @param url the URL of the image%0A     */%0A
     private void

add javadoc