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

import java.io.File;
import java.io.FileInputStream;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import cn.net.caoyao.cpzshandset.common.config.SDCardConfig;

public class ClearCacheUtil {
//	清除的目录包括：
//	1./data/data/package_name/files
//	2./data/data/package_name/cache
//	3.<sdcard>/Android/data/<package_name>/cache/
	private String filePath = "/data/data/package_name/files";
	private static Context context;
	public static void clearCache(Context context){
		// 计算缓存大小
		long fileSize = 0;
		String cacheSize = "0KB";
		File filesDir = getFilesDir();// /data/data/package_name/files
		File cacheDir = getCacheDir();// /data/data/package_name/cache

		fileSize += getDirSize(filesDir);  
	    fileSize += getDirSize(cacheDir);  

	//2.2版本才有将应用缓存转移到sd卡的功能  

	    if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){  

	        File externalCacheDir = getExternalCacheDir(context);//"<sdcard>/Android/data/<package_name>/cache/"  
	        fileSize += getDirSize(externalCacheDir);             

	    }  

	   if (fileSize > 0)  
	        cacheSize = formatFileSize(fileSize);
	}
	

	private static File getCacheDir() {
		// TODO Auto-generated method stub
		return new File(SDCardConfig.getCachePath(context));
	}
	private static File getFilesDir() {
		// TODO Auto-generated method stub
		return new File(SDCardConfig.getFileCachePath(context));
	}
	/**
	 * 获取目录文件大小
	 * 
	 * @param dir
	 * @return
	 */
	public static long getDirSize(File dir) {
		if (dir == null) {
			return 0;
		}
		if (!dir.isDirectory()) {
			return 0;
		}
		long dirSize = 0;
		File[] files = dir.listFiles();
		for (File file : files) {
			if (file.isFile()) {
				dirSize += file.length();
			} else if (file.isDirectory()) {
				dirSize += file.length();
				dirSize += getDirSize(file); // 递归调用继续统计
			}
		}
		return dirSize;
	}

	/**
	 * 判断当前版本是否兼容目标版本的方法
	 * 
	 * @param VersionCode
	 * @return
	 */
	public static boolean isMethodsCompat(int VersionCode) {
		int currentVersion = android.os.Build.VERSION.SDK_INT;
		return currentVersion >= VersionCode;
	}

	@TargetApi(8)
	public static File getExternalCacheDir(Context context) {

		// return context.getExternalCacheDir(); API level 8

		// e.g. "<sdcard>/Android/data/<package_name>/cache/"

		return context.getExternalCacheDir();
	}

	/**
	 * 转换文件大小
	 * 
	 * @param fileS
	 * @return B/KB/MB/GB
	 */
	public static String formatFileSize(long fileS) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 清除app缓存
	 * 
	 * @param activity
	 */
	public static void clearAppCache(Activity activity) {
		final Context ac =  activity.getApplication();
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
//					ToastMessage(ac, "缓存清除成功");
					Toast.makeText(context, "缓存清除成功", Toast.LENGTH_SHORT).show();
				} else {
//					ToastMessage(ac, "缓存清除失败");
					Toast.makeText(context, "缓存清除失败", Toast.LENGTH_SHORT).show();
				}
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
//					ac.clearAppCache();
					msg.what = 1;
				} catch (Exception e) {
					e.printStackTrace();
					msg.what = -1;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}

/*在项目中经常会使用到WebView 控件,当加载html 页面时,会在/data/data/
	package_name目录下生成database与cache 两个文件夹。
	请求的url 记录是保存在WebViewCache.db,
	而url 的内容是保存在WebViewCache 文件夹下*/

	/**
	 * 清除app缓存
	 */
	public void clearAppCache() {
		// 清除webview缓存
		@SuppressWarnings("deprecation")
		File file = new File(SDCardConfig.getCachePath(context));

		// 先删除WebViewCache目录下的文件

		if (file != null && file.exists() && file.isDirectory()) {
			for (File item : file.listFiles()) {
				item.delete();
			}
			file.delete();
		}
		context.deleteDatabase("webview.db");
		context.deleteDatabase("webview.db-shm");
		context.deleteDatabase("webview.db-wal");
		context.deleteDatabase("webviewCache.db");
		context.deleteDatabase("webviewCache.db-shm");
		context.deleteDatabase("webviewCache.db-wal");
		// 清除数据缓存
		clearCacheFolder(getFilesDir(), System.currentTimeMillis());
		clearCacheFolder(getCacheDir(), System.currentTimeMillis());
		// 2.2版本才有将应用缓存转移到sd卡的功能
		if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
			clearCacheFolder(getExternalCacheDir(context), System.currentTimeMillis());
		}

	}

	/**
	 * 清除缓存目录
	 * 
	 * @param dir
	 *            目录
	 * @param numDays
	 *            当前系统时间
	 * @return
	 */
	private int clearCacheFolder(File dir, long curTime) {
		int deletedFiles = 0;
		if (dir != null && dir.isDirectory()) {
			try {
				for (File child : dir.listFiles()) {
					if (child.isDirectory()) {
						deletedFiles += clearCacheFolder(child, curTime);
					}
					if (child.lastModified() < curTime) {
						if (child.delete()) {
							deletedFiles++;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return deletedFiles;
	}

	// modify by echo at 2016年3月24日17:19:18
	/**
	 * 获取指定文件夹
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	private static long getFileSizes(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSizes(flist[i]);
			} else {
				size = size + getFileSize(flist[i]);
			}
		}
		return size;
	}
	/**
	 * 获取指定文件大小
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	private static long getFileSize(File file) throws Exception {
		long size = 0;
		if (file.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			size = fis.available();
		} else {
			file.createNewFile();
			Log.e("获取文件大小", "文件不存在!");
		}
		return size;
	}
}
