package com.sipai.jspatrol.utils;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;

public class AsyncImageLoader {
	private Object lock = new Object();
	private boolean mAllowLoad = true;
	private boolean firstLoad = true;
	private int mStartLoadLimit = 0;
	private int mStopLoadLimit = 0;
	final Handler handler = new Handler();

	private HashMap<String, SoftReference<Drawable>> imageCache;

	public AsyncImageLoader() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	public void setLoadLimit(int startLoadLimit, int stopLoadLimit) {
		if (startLoadLimit > stopLoadLimit) {
			return;
		}
		mStartLoadLimit = startLoadLimit;
		mStopLoadLimit = stopLoadLimit;
	}

	public void restore() {
		mAllowLoad = true;
		firstLoad = true;
	}

	public void lock() {
		mAllowLoad = false;
		firstLoad = false;
	}

	public void unlock() {
		mAllowLoad = true;
		synchronized (lock) {
			lock.notifyAll();
		}
	}

public Drawable loadDrawable(final Integer pos, final String imageUrl,
		 final ImageCallback imageCallback) {
	new Thread() {
		@Override
		public void run() {
			if (!mAllowLoad) {// 先阻塞线程
				synchronized (lock) {// 加锁
					try {
						lock.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			// 如果是第一次加载XML就加载图片，对于是不是在显示范围内的加载控制放在VIEW中
			if (mAllowLoad && firstLoad) {
				LoadImg(pos, imageUrl, imageCallback);
			}
			// 对于在显示范围内的，对其加载IMG
			if (mAllowLoad && pos <= mStopLoadLimit
					&& pos >= mStartLoadLimit) {
				LoadImg(pos, imageUrl, imageCallback);
			}

		}
	}.start();
	return null;
}// loadDrawable---end

	public void LoadImg(final Integer pos, final String imageUrl,
			final ImageCallback imageCallback) {
		// 首先判断是否在缓存中
		// 但有个问题是：ImageCache可能会越来越大，以至用户内存用光，所以要用SoftReference（弱引用）来实现
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			final Drawable drawable = softReference.get();
			if (drawable != null) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						if (mAllowLoad) {
							imageCallback.onImageLoad(pos, drawable);
							Log.d("msg","缓存加载的"+imageUrl+";POS:"+pos);
						}else {
							imageCallback.onError(pos);
						}
					}
				});
				return;
			}
		}
		// 尝试从URL中加载
		try {
			final Drawable drawable = loadImageFromUrl(imageUrl);
			if (drawable != null) {
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
			}
			handler.post(new Runnable() {
				@Override
				public void run() {
					if (mAllowLoad) {
						Log.d("msg","网上加载的"+imageUrl+";POS:"+pos);
						imageCallback.onImageLoad(pos, drawable);
					}
				}
			});
		} catch (IOException e) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					imageCallback.onError(pos);
				}
			});
			e.printStackTrace();
		}

	}

	// 根据URL加载图片,如果出现错误throws IOException式的错误，以便在LoadImg中捕获，执行OnError（）函数
	public static Drawable loadImageFromUrl(String url) throws IOException {
		URL m;
		InputStream i = null;
		m = new URL(url);
		i = (InputStream) m.getContent();
		Drawable d = Drawable.createFromStream(i, "src");
		return d;
	}

	// 回调函数
	public interface ImageCallback {
		void onImageLoad(Integer t, Drawable drawable);
		void onError(Integer t);
	}

}
