package com.backfire.doudizhu.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.backfire.utils.Log;
import com.backfire.utils.MyAsyncTask;
import com.backfire.utils.MyTaskWrap;

public class DownLoadImage{
	private static final String LOG_PATH = "backfire";
	private static final String PNG_SUFFIX = ".png";

	private static byte[] sync = new byte[0];

	private static String getTempPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator + LOG_PATH;
	}

	private static boolean testSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}
	private static boolean deleteFile(String name) {
		File file = new File(name);
		if (file.exists()) {
			return file.delete();
		}
		return false;
	}

	private static void  saveBitmap(final Context context, final String fileName, final Bitmap bmp) {
		new MyAsyncTask(new MyTaskWrap() {
			@Override
			public void onTaskStart() {
				try {
					if (null == fileName || 0 == fileName.length())
						return ;
					if (null == bmp)
						return ;
					if (bmp.isRecycled())
						return ;
					
					String fullName = null;
					FileOutputStream fOut = null;
					File file = null;
					
					if (testSDCard()) {	//如果存在SD卡，则在SD卡中读取文件
						fullName = getTempPath() + File.separator + fileName
								+ PNG_SUFFIX;
						deleteFile(fileName);
						file = new File(fullName);
						if(!file.getParentFile().exists()) file.getParentFile().mkdirs();
						fOut = new FileOutputStream(file);
						Log.i("保存图片到SD卡中", fullName);
					}else{	//如果不存在SD卡，则直接在应用程序内存中读取文件
						context.deleteFile(fileName + PNG_SUFFIX);
						file = new File(context.getCacheDir(), fileName + PNG_SUFFIX);
						try {
							fullName = file.getCanonicalPath();
						} catch (Exception e) {
						}
						fOut = context.openFileOutput(fileName + PNG_SUFFIX, Context.MODE_WORLD_READABLE);
						Log.i("保存图片到data中", fileName + PNG_SUFFIX);
					}
					bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
					try {
						fOut.flush();
						fOut.close();
						fOut = null;
					} catch (IOException e) {
						Log.e("SDTools", e);
						return ;
					} finally {
						try {
							if (null != fOut)
								fOut.close();
						} catch (Exception e) {
						}
					}
				} catch (Exception e) {
				}
			}
			
			@Override
			public void onTaskFinish() {

			}
		}).execute();
	}
	public static void saveBitmap(final Context context, final String fileName, final String url,final DownLoadImageListener listener) {
		new MyAsyncTask(new MyTaskWrap() {
			private Bitmap result = null;
			@Override
			public void onTaskStart() {
				try {
					if (null == fileName || 0 == fileName.length())
					{
						return ;
					}
					if (null == url || 0 == url.length()){
						return ;
					}
					URL Url = new URL(url);
					URLConnection conn = Url.openConnection();
					conn.connect();
					conn.setConnectTimeout(20*1000);//连接超时控制
					InputStream is = conn.getInputStream();
					result = BitmapFactory.decodeStream(is);
				} catch (Exception e) {
					Log.e(this, e);
				}
			}
			
			@Override
			public void onTaskFinish() {
				if(result!=null){
					saveBitmap(context,fileName,result);
					listener.onFinish(result);
				}else{
					listener.onFailed();
				}
			}
		}).execute();
	}

	public static Bitmap loadBitmap(Context context, String fileName) {
		synchronized (sync) {
			if (null == fileName || 0 == fileName.length())
				return null;
			if (testSDCard()) {	//如果存在SD卡，则在SD卡中读取文件
				String path = getTempPath() + File.separator + fileName
						+ PNG_SUFFIX;
				try {
					return BitmapFactory.decodeFile(path);
				} catch (Exception e) {
					Log.e("loadBitmap....", e);
					return null;
				}
			}else{	//如果不存在SD卡，则直接在应用程序内存中读取文件
				File ret = new File(context.getCacheDir(), fileName + PNG_SUFFIX);
				try {
					if(ret.exists()){
						return BitmapFactory.decodeFile(ret.getCanonicalPath());
					}else{
						return null;
					}
				} catch (Exception e) {
					return null;
				}
			}
		}
	}
	
	public static String loadBitmapPath(Context context,String fileName){
		synchronized (sync) {
			if (null == fileName || 0 == fileName.length())
				return null;
			if (testSDCard()) {	//如果存在SD卡，则在SD卡中读取文件
				String path = getTempPath() + File.separator + fileName
						+ PNG_SUFFIX;
				return path;
			}else{	//如果不存在SD卡，则直接在应用程序内存中读取文件
				File ret = new File(context.getCacheDir(), fileName + PNG_SUFFIX);
				try {
					if(ret.exists()){
						return ret.getCanonicalPath();
					}else{
						return null;
					}
				} catch (Exception e) {
					return null;
				}
			}
		}
	}
}

