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

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Environment;
import android.util.Log;
import cn.net.caoyao.cpzshandset.common.config.SDCardConfig;
import cn.net.caoyao.cpzshandset.common.config.TConfig;



public class LogUtil {
	public static final String CACHE_DIR_NAME = "ZGZCConsumer";

	public static boolean isDebugModel = TConfig.debugerLog;// 是否输出日志
	public static boolean isSaveDebugInfo = TConfig.isSaveDebugInfo;// 是否保存调试日志
	public static boolean isSaveCrashInfo = TConfig.isSaveCrashInfo;// 是否保存报错日志
	// 错误日志记录位置
	public static String path = SDCardConfig.getSDPathForLog() + "UncaughtExceptions/" + DateUtil.getDataForLog();


	/** 日志级别 显示级别参考 android.util.Log的级别 配置0全部显示，配置大于7全不显示 */
	public static final int LEVLE = 0;

	//<ql/>
	public static void d(String tag, Object... msg) {
		if (isDebugModel) {
			if (LEVLE <= Log.DEBUG) {
				String throwable = getThrowable(msg);
				Log.d(tag, throwable);
				String line = "DEBUG" + "\t" + getLogTime() + "\t" + tag + "\t"
						+ throwable;
				writeLine(line);
			}

		}
	}

	public static void writeLine(String line) {
		File file = getFileForCash();
		if (file.exists() && file.length() > 1024 * 40) {// 超过40k就删除
			file.delete();
		}

		FileWriter writer = null;
		try {
			writer = new FileWriter(file, true);
			writer.write(line + "\n");
			writer.flush();
		} catch (IOException e) {
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static File getFileForCash() {
		SimpleDateFormat logFt = new SimpleDateFormat("yyyyMMdd");
		long timestamp = System.currentTimeMillis();
		Date d = new Date(timestamp);
		// String time = formatter.format(new Date());
		String time = logFt.format(d);
		// String fileName = "crash-" + time + "-" + timestamp + ".txt";
		String fileName = "crash-" + time + ".txt";
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File f = new File(path + fileName);
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return f;
	}
	public static String getLogTime() {
		SimpleDateFormat logFt = (SimpleDateFormat) DateFormat.getDateInstance();
		logFt.applyPattern("MM-dd kk:mm:ss");
//		SimpleDateFormat logFt = new SimpleDateFormat("MM-dd kk:mm:ss");
		long timestamp = System.currentTimeMillis();
		Date d = new Date(timestamp);
		String time = logFt.format(d);
		return time;

	}
	public static String getThrowable(Object... msg) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (Object o : msg) {
			if (i > 0) {
				sb.append(',');
			}
			sb.append(o == null ? "null" : o.toString());
			i++;
		}

		int logStrLength = sb.length();
		int maxLogSize = 1000;
		for (i = 0; i <= logStrLength / maxLogSize; i++) {
			int start = i * maxLogSize;
			int end = (i + 1) * maxLogSize;
			end = end > logStrLength ? logStrLength : end;
			return sb.substring(start, end);
		}
		return null;
	}
	public static void v(final String tag, final String msg) {
		if (isDebugModel) {
			Log.v(tag, "--> " + msg);
		}
		if (isSaveDebugInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " --> " + msg + "\n");
				};
			}.start();
		}
	}

	public static void d(final String tag, final String msg) {
		if (isDebugModel) {
			Log.d(tag, "--> " + msg);
		}
		if (isSaveDebugInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " --> " + msg + "\n");
				};
			}.start();
		}
	}

	public static void i(final String tag, final String msg) {
		//<ql>
		/*if ((LogOperations & LogOperationI) == LogOperationI) {
			Log.i(tag, "--> " + msg);
		}*/
		//<ql/>
		
		
		if (isDebugModel) {
			Log.i(tag, "--> " + msg);
		}
		if (isSaveDebugInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " --> " + msg + "\n");
				};
			}.start();
		}
	}

	public static void w(final String tag, final String msg) {
		if (isDebugModel) {
			Log.w(tag, "--> " + msg);
		}
	}

	public static void w(final String tag, final String msg, final Throwable t) {
		if (isDebugModel) {
			Log.w(tag, "--> " + msg);
		}

		if (isSaveDebugInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " --> " + msg + "\n");
				};
			}.start();
		}
	}

	/**
	 * 调试日志，便于开发跟踪。
	 * 
	 * @param tag
	 * @param msg
	 */
	public static void e(final String tag, final String msg) {
		if (isDebugModel) {
			Log.e(tag, "--> " + msg);
		}

		if (isSaveDebugInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " --> " + msg + "\n");
				};
			}.start();
		}
	}

	/**
	 * try catch 时使用，上线产品可上传反馈。
	 * 
	 * @param tag
	 * @param tr
	 */
	public static void e(final String tag, final Throwable tr) {
		if (isSaveCrashInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " [CRASH] --> " + getStackTraceString(tr) + "\n");
				};
			}.start();
		}
	}

	/**
	 * try catch 时使用，上线产品可上传反馈。
	 * 
	 * @param tag
	 * @param tr
	 */
	public static void e(final String tag, final String msg, final Throwable tr) {
		if (isSaveCrashInfo) {
			new Thread() {
				public void run() {
					write(time() + tag + " [CRASH] --> " + getStackTraceString(tr) + "\n");
				};
			}.start();
		}
	}

	/**
	 * 获取捕捉到的异常的字符串
	 * 
	 * @param tr
	 * @return
	 */
	public static String getStackTraceString(Throwable tr) {
		if (tr == null) {
			return "";
		}

		Throwable t = tr;
		while (t != null) {
			if (t instanceof UnknownHostException) {
				return "";
			}
			t = t.getCause();
		}

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		tr.printStackTrace(pw);
		return sw.toString();

	}

	/**
	 * 标识每条日志产生的时间
	 * 
	 * @return
	 */
	private static String time() {
		return "[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())) + "] ";
	}

	/**
	 * 以年月日作为日志文件名称
	 * 
	 * @return
	 */
	private static String date() {
		return new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
	}

	/**
	 * 保存到日志文件
	 * 
	 * @param content
	 */
	public static synchronized void write(String content) {
		try {
			FileWriter writer = new FileWriter(getFile(), true);
			writer.write(content);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取日志文件路径
	 * 
	 * @return
	 */
	public static String getFile() {
		File sdDir = null;

		if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
			sdDir = Environment.getExternalStorageDirectory();

		File cacheDir = new File(sdDir + File.separator + CACHE_DIR_NAME);
		if (!cacheDir.exists())
			cacheDir.mkdir();

		File filePath = new File(cacheDir + File.separator + date() + ".txt");

		return filePath.toString();
	}

}
