package com.qiyou.mb.android.utils;

import java.io.File;
import java.io.IOException;

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

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

public class FileCache {
	public static final String TAG = "com.qiyou.mb.android.utils.FileCache";
	public static final String dTAG = "com.qiyou";
	private File cacheDir;

	public FileCache(Context context) {
		// 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
		// 没有SD卡就放在系统的缓存目录中
//		try{
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			cacheDir = new File(
					QiYouConstant.SD_PATH,
					"picCache");
		else
			cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();
		/*}catch(Exception e){
			Utils.logStackTrace(e, TAG);
		}*/
	}

	public File getFile(String url) {
		// 将url的hashCode作为缓存的文件名
		if(TextUtils.isEmpty(url))return null;
		String filename = String.valueOf(url.hashCode());
		// Another possible solution
		// String filename = URLEncoder.encode(url);
		File f = new File(cacheDir, filename);
		return f;

	}

	public File getLocalMdFile(String url) {
//		QLog.getLogger().d(dTAG, TAG +", url is: "+url);
		File f = new File(url);
		if(f.exists())
		return f;
		else
			return getFile(url);

	}

	
	public void clear() {
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
	}
	
	public Uri getCachedUri(String fileUrl){
		File f =getLocalMdFile(fileUrl);
		File ff = new File(cacheDir, "share.png");
		if(f.exists()){
			 
			try {
				FileUtil.copyFile(f,ff);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return Uri.fromFile(ff);
//		return Uri.fromFile(getLocalMdFile(fileUrl));
	}

}