package com.qiyou.mb.android.utils;

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.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.widget.ImageView;

import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.utils.log.QLog;

public class ImageLoader {
	public static final String TAG = "com.qiyou.mb.android.utils.ImageLoader";
	public static final String dTAG = "com.qiyou";
	MemoryCache memoryCache = new MemoryCache();
	FileCache fileCache;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	// 线程池
	ExecutorService executorService;

	public ImageLoader(Context context) {
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
	}

	// 当进入listview时默认的图片，可换成你自己的默认图片
	final int stub_id = R.drawable.icon_riding64;//.empty_photo;
    final int SIZE=QiYouConstant.SUBNAIL_PIC_SIZE;
	// 最主要的方法
	public void DisplayImage(String url, ImageView imageView) {
		imageViews.put(imageView, url);
		// 先从内存缓存中查找
//		QLog.getLogger().d(dTAG, TAG+" url is:"+url);
		Bitmap bitmap = memoryCache.get(url);
		
		if (bitmap != null){
			QLog.getLogger().d(dTAG, TAG+" Get the Img from cache.");
			imageView.setImageBitmap(bitmap);
		}
		else {
			// 若没有的话则开启新线程加载图片
			QLog.getLogger().d(dTAG, TAG+" Img not exist in cache, start to load it.");
			queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
		}
	}

	/*public static void createSmallPic(final String picName,final int SMALLSIZE){
	 final int SMALLSIZE=480;
	 new Thread(new Runnable(){
	    @Override
	    public void run() {
	    	  com.qiyou.mb.android.utils.ImageLoader IL = new com.qiyou.mb.android.utils.ImageLoader(activity);
	    	  
	    	 Bitmap b= IL.getBitmap(picName, SMALLSIZE);
	    	  b= watermarkBitmap(b,null,QiYouConstant.MAP_PIC_WATER_MARK_WORDS); 
	    	  String smallPicName=picName.substring(0,picName.lastIndexOf(".jpg"))+SMALLSIZE+".jpg";
			  File file = new File(smallPicName);
	         FileOutputStream out;
	         try{
	             out = new FileOutputStream(file);
	             if(b.compress(Bitmap.CompressFormat.PNG, 70, out)) 
	             {
	                 out.flush();
	                 out.close();
	             }  
	           
	         } 
	         catch (FileNotFoundException e) 
	         {
	             e.printStackTrace();
	         } 
	         catch (IOException e) 
	         {
	             e.printStackTrace(); 
	         }
	    	  
	    }
	 	}).start();
	}*/
 
	private void queuePhoto(String url, ImageView imageView) {
		PhotoToLoad p = new PhotoToLoad(url, imageView);
		
		executorService.submit(new PhotosLoader(p));
	}

	public Bitmap getBitmap(String url ) {
		return getBitmap(url,SIZE); 
	}
	
	public Bitmap getBitmap(String url,int size) {
//		File f = fileCache.getFile(url);
		if(TextUtils.isEmpty(url))return null;
//		QLog.getLogger().d(dTAG, TAG +", url is: "+url);
		File f = fileCache.getLocalMdFile(url);
		
		// 先从文件缓存中查找是否有
		Bitmap b = decodeFile(f,size);
		if (b != null)
			return b;

		// 最后从指定的url中下载图片
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			CopyStream(is, os);
			os.close();
			bitmap = decodeFile(f,size);
			return bitmap;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	private Bitmap decodeFile(File f) {
	
		return decodeFile(f,SIZE);
	}
	// decode这个图片并且按比例缩放以减少内存消耗，虚拟机对每张图片的缓存大小也是有限制的
	private Bitmap decodeFile(File f,int size) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			FileInputStream is =new FileInputStream(f);
			BitmapFactory.decodeStream(is, null, o);
			is.close();
//			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE =size;// 20;//70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
		/*	while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}*/
			
			while  (width_tmp / 2 > REQUIRED_SIZE
					|| height_tmp / 2 > REQUIRED_SIZE) {
				 
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
//			QLog.getLogger().d(dTAG,TAG +"Picture inSampleSize scale is:" + scale);
//			FileInputStream is =new FileInputStream(f);
			 is =new FileInputStream(f);
			Bitmap b = BitmapFactory.decodeStream(is, null, o2);
			is.close();
			return b;
//			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
		}
		return null;
	}
	
	 
	
	
	/*private Bitmap decodeBitmp(){
		 Display display=getWindowManager().getDefaultDisplay();
         int dw=display.getWidth();
         int dh=display.getHeight();
         
         //加载图像
         BitmapFactory.Options options=new BitmapFactory.Options();
         options.inJustDecodeBounds=true;//设置之后可以设置长宽
         Bitmap bitmap=BitmapFactory.decodeFile(imageFilePath, options);
         
         int heightRatio=(int)Math.ceil(options.outHeight/(float)dh);
         int widthRatio=(int)Math.ceil(options.outWidth/(float)dw);
         
         QLog.getLogger().d(TAG, dTAG+ " heith:"+heightRatio);
         QLog.getLogger().d(TAG,dTAG+" width:"+widthRatio);
         //判断长宽哪个大
         if(heightRatio>1 && widthRatio>1){
             if(heightRatio>widthRatio){
                 options.inSampleSize=heightRatio;
             }else{
                 options.inSampleSize=widthRatio;
             }
         }
         //对它进行真正的解码
         options.inJustDecodeBounds=false;
         bitmap=BitmapFactory.decodeFile(imageFilePath, options);
	}
	*/
	

	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;

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

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			Bitmap bmp = getBitmap(photoToLoad.url);
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			// 更新的操作放在UI线程中
			Activity a = (Activity) photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	/**
	 * 防止图片错位
	 * 
	 * @param photoToLoad
	 * @return
	 */
	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	// 用于在UI线程中更新界面
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

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

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
			else
				photoToLoad.imageView.setImageResource(stub_id);
		}
	}

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

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