package cn.net.caoyao.cpzshandset.common.bitmap;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;

public class ImageLoader {
	private MemoryCache memoryCache = new MemoryCache();
	private FileCache fileCache;
	private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap());
	private ExecutorService executorService;
	private boolean isLoadOnlyFromCache = false;
	private ArrayList<Integer> myList = null;
	private boolean isdownload = false;

	public ImageLoader(String cachePath) {
		this.myList = new ArrayList();
		this.fileCache = new FileCache(cachePath);
		this.executorService = Executors.newFixedThreadPool(3);
	}
	
	public void DisplayImage(String url, ImageView imageView, boolean isC, int w, int h, float r) {
		this.imageViews.put(imageView, url);

		Bitmap bitmap = this.memoryCache.get(url);
		if (bitmap != null) {
			imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
		} else if (!this.isLoadOnlyFromCache) {
			queuePhoto(url, imageView, isC, w, h, r);
		}
	}

	public Bitmap createFramedPhoto(int x, int y, Bitmap image, float outerRadiusRat) {
		Drawable imageDrawable = new BitmapDrawable(image);

		Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		RectF outerRect = new RectF(0.0F, 0.0F, x, y);

		Paint paint = new Paint(1);
		paint.setColor(-65536);
		canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		imageDrawable.setBounds(0, 0, x, y);
		canvas.saveLayer(outerRect, paint, 31);
		imageDrawable.draw(canvas);
		canvas.restore();

		return output;
	}

	@SuppressLint({ "UseValueOf" })
	public void DisplayNetImage(String url, ImageView imageView, int index, int count, boolean isC, int x, int y,
			float r) {
		this.imageViews.put(imageView, url);

		Bitmap bitmap = this.memoryCache.get(url);
		if (bitmap != null) {
			imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
		} else if (!this.isLoadOnlyFromCache) {
			if (this.myList.isEmpty()) {
				this.myList.add(Integer.valueOf(index));
				this.isdownload = true;
			} else {
				int flog = new Integer(((Integer) this.myList.get(this.myList.size() - 1)).toString()).intValue();
				if ((flog + 1 == index) && (this.myList.size() <= count)) {
					this.myList.add(Integer.valueOf(index));
					this.isdownload = true;
				}
			}

			if (this.isdownload) {
				queuePhoto(url, imageView, isC, x, y, r);
				this.isdownload = false;
			}
		}
	}

	private void queuePhoto(String url, ImageView imageView, boolean isC, int x, int y, float r) {
		PhotoToLoad p = new PhotoToLoad(url, imageView, isC, x, y, r);
		this.executorService.submit(new PhotosLoader(p));
	}

	public static Bitmap returnBitMap(String url, boolean isCut, int x, int y, float outerRadiusRat) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);

			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();

			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	private Bitmap getBitmap(String url, boolean isCut, int x, int y, float outerRadiusRat) {
		File f = this.fileCache.getFile(url);

		Bitmap b = null;
		if ((f != null) && (f.exists())) {
			b = decodeFile(f);
		}
		if (b != null) {
			return b;
		}
		try {
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			Bitmap bitmap1 = null;
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			InputStream isBm = null;
			if (isCut) {
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				bitmap1 = createFramedPhoto(x, y, bitmap, outerRadiusRat);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				bitmap1.compress(Bitmap.CompressFormat.PNG, 100, baos);

				isBm = new ByteArrayInputStream(baos.toByteArray());
				CopyStream(isBm, os);
			} else {
				CopyStream(is, os);
				bitmap1 = decodeFile(f);
			}
			os.close();
			return bitmap1;
		} catch (Exception ex) {
			LogUtil.e("ImageLoder", "getBitmap catch Exception...\nmessage = " + ex.getMessage());
		}
		return null;
	}

	private Bitmap decodeFile(File f) {
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			int REQUIRED_SIZE = 100;
			int width_tmp = o.outWidth;
			int height_tmp = o.outHeight;
			int scale = 1;

			while ((width_tmp / 2 >= 100) && (height_tmp / 2 >= 100)) {
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException localFileNotFoundException) {
		}
		return null;
	}

	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = (String) this.imageViews.get(photoToLoad.imageView);

		return (tag == null) || (!tag.equals(photoToLoad.url));
	}

	public void clearCache() {
		this.memoryCache.clear();
		this.fileCache.clear();
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		int buffer_size = 1024;
		try {
			byte[] bytes = new byte[1024];
			while (true) {
				int count = is.read(bytes, 0, 1024);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
			LogUtil.e("ImageLoder", "CopyStream catch Exception...");
		}
	}

	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		ImageLoader.PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, ImageLoader.PhotoToLoad p) {
			this.bitmap = b;
			this.photoToLoad = p;
		}

		public void run() {
			if (ImageLoader.this.imageViewReused(this.photoToLoad))
				return;
			if (this.bitmap != null) {
				this.photoToLoad.imageView.setBackgroundDrawable(new BitmapDrawable(this.bitmap));
			}
		}
	}

	private class PhotoToLoad {
		public String url;
		public ImageView imageView;
		public boolean isCut;
		public int X;
		public int Y;
		public float R;

		public PhotoToLoad(String u, ImageView i, boolean isC, int x, int y, float r) {
			this.url = u;
			this.imageView = i;
			this.isCut = isC;
			this.X = x;
			this.Y = y;
			this.R = r;
		}
	}

	class PhotosLoader implements Runnable {
		ImageLoader.PhotoToLoad photoToLoad;

		PhotosLoader(ImageLoader.PhotoToLoad photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		public void run() {
			if (ImageLoader.this.imageViewReused(this.photoToLoad))
				return;
			Bitmap bmp = ImageLoader.this.getBitmap(this.photoToLoad.url, this.photoToLoad.isCut, this.photoToLoad.X,
					this.photoToLoad.Y, this.photoToLoad.R);
			ImageLoader.this.memoryCache.put(this.photoToLoad.url, bmp);
			if (ImageLoader.this.imageViewReused(this.photoToLoad))
				return;
			ImageLoader.BitmapDisplayer bd = new ImageLoader.BitmapDisplayer(bmp, this.photoToLoad);
//			ImageLoader.BitmapDisplayer bd = new ImageLoader.BitmapDisplayer(ImageLoader.this, bmp, this.photoToLoad);

			Activity a = (Activity) this.photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}
}