package net.x4a42.volksempfaenger.ui;

import net.x4a42.volksempfaenger.R;
import net.x4a42.volksempfaenger.Utils;
import net.x4a42.volksempfaenger.data.CacheMap;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

public class PodcastLogoView extends ImageView {

	private static CacheMap<Long, Bitmap> cache = new CacheMap<Long, Bitmap>();

	private long podcastId;
	private AsyncTask<Void, Void, Bitmap> lastTask;

	public PodcastLogoView(Context context) {
		super(context);
		init();
	}

	public PodcastLogoView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

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

	private void init() {
		setImageResource(R.drawable.default_logo);
	}

	public void setPodcastId(long id) {
		if (id == podcastId) {
			// don't reload the logo
			return;
		}

		if (lastTask != null) {
			lastTask.cancel(false);
		}

		Bitmap logo = cache.get(id);
		if (logo != null) {
			// the logo is cached, we don't need to fire off an AsyncTask
			setImageBitmap(logo);
		} else {
			lastTask = new LoadTask(id).execute();
		}

		podcastId = id;
	}

	public long getPodcastId() {
		return podcastId;
	}

	private class LoadTask extends AsyncTask<Void, Void, Bitmap> {

		private long id;

		private LoadTask(long id) {
			this.id = id;
		}

		@Override
		protected Bitmap doInBackground(Void... params) {
			return Utils.getPodcastLogoBitmap(getContext(), id);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				setImageBitmap(result);
				cache.put(id, result);
			} else {
				setImageResource(R.drawable.default_logo);
			}
		}

		@Override
		protected void onCancelled(Bitmap result) {
			init();
			cache.put(id, result);
		}

	}

}

@@ -579,27 +579,28 @@
 context);%0A%09%09
-ini
+rese
 t();%0A%09%7D%0A%0A%09pu
@@ -682,27 +682,28 @@
 , attrs);%0A%09%09
-ini
+rese
 t();%0A%09%7D%0A%0A%09pu
@@ -813,19 +813,20 @@
 yle);%0A%09%09
-ini
+rese
 t();%0A%09%7D%0A
@@ -840,19 +840,20 @@
 te void 
-ini
+rese
 t() %7B%0A%09%09
@@ -1057,24 +1057,47 @@
 (false);%0A%09%09%7D
+ else %7B%0A%09%09%09reset();%0A%09%09%7D
 %0A%0A%09%09Bitmap l
@@ -1785,48 +1785,14 @@
 %09%09%09%09
-setImageResource(R.drawable.default_logo
+reset(
 );%0A%09
@@ -1865,16 +1865,43 @@
 %0A%09%09%09
-ini
+rese
 t();%0A
+%09%09%09if (result != null) %7B%0A%09
 %09%09%09c
@@ -1922,16 +1922,21 @@
 esult);%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%0A%09%7D%0A

Break some more stuff.