package com.usai.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.usai.redant.photo.RedAntApplication;
import com.usai.redant.photo.R.string;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.util.Log;

public class dbgUtil
{
	// static boolean ENABLE_DEBUG = true;
	// static boolean ENABLE_SQL_DEBUG = true;
	// final int DEBUG_LEVEL_NONE = 8;
	// static int DEBUG_LEVEL = Log.VERBOSE;

	// private static boolean m_dbgFlag = true;
	/*
	 * public dbgUtil(Context context) {
	 * 
	 * m_dbgFlag = Boolean.parseBoolean(context.getString(R.string.flag_debug));
	 * 
	 * }
	 * 
	 * public dbgUtil(Context context) { m_dbgFlag =
	 * Boolean.parseBoolean(context.getString(R.string.flag_debug)); return
	 * this; }
	 */
	public static void fileLog(String content)
	{
		
		File dir = new File(Environment.getExternalStorageDirectory().getPath()
				+ "/redant/pop");
		if (!dir.exists())
			dir.mkdirs();

		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONDAY, -1);

		String newtime = new SimpleDateFormat("yyyy-MM-dd").format(c
				.getTimeInMillis());

		File[] f = dir.listFiles();
		for (int i = 0; i < f.length; i++)
		{
			if(!f[i].isFile())
				continue;
			String n = f[i].getName();
			if ((n != null) && (n.length() > 0))
			{
				int dot = n.lastIndexOf('.');
				if ((dot > -1) && (dot < (n.length())))
				{
					n = n.substring(0, dot);
				}
				if(newtime.compareTo(n)>0)
					f[i].delete();
				


			}
		}

		// dir.listfiles

		String file = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());

		FileOutputStream outputStream = null;
		// try
		// {

		// dir.createNewFile()
		File logfile = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/redant/pop/" + file + ".log");

		// int mode = Application.MODE_APPEND;
		if (!logfile.exists())
		{
			// mode = Application.MODE_PRIVATE;
			try
			{
				logfile.createNewFile();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// outputStream
		// =RedAntApplication.getInstance().openFileOutput("pop.log", mode);

		String logtextString = timeStamp + "   " + content;

		FileWriter fw = null;
		BufferedWriter bw = null;
		String datetime = "";
		try
		{
			RedAntApplication.loglock.writeLock().lock();

			fw = new FileWriter(Environment.getExternalStorageDirectory()
					.getPath() + "/redant/pop/" + file + ".log", true);//
			// 创建FileWriter对象，用来写入字符流
			bw = new BufferedWriter(fw); // 将缓冲对文件的输出
			// String myreadline = datetime + "[]" + str;

			bw.write(logtextString + "\n"); // 写入文件
			bw.newLine();
			bw.flush(); // 刷新该流的缓冲
			bw.close();
			fw.close();
			RedAntApplication.loglock.writeLock().unlock();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			try
			{
				bw.close();
				fw.close();
			}
			catch (IOException e1)
			{
				// TODO Auto-generated catch block
			}
		}

	}

	public static void Logd(String tag, String msg)
	{
		String pos = getTracePos();
		Log.d(tag, msg + pos);
	}

	// public static void Log(int type, String tag, String msg)
	// {
	// // if (ENABLE_DEBUG == false)
	// // return;
	// // if (type < DEBUG_LEVEL)
	// // return;
	// String pos= getTracePos();
	// switch (type)
	// {
	// case Log.ASSERT:
	// Log.wtf(tag, msg+pos);
	// break;
	// case Log.DEBUG:
	// Log.d(tag, msg+pos);
	// break;
	// case Log.ERROR:
	// Log.e(tag, msg+pos);
	// break;
	// case Log.INFO:
	// Log.i(tag, msg+pos);
	// break;
	// case Log.VERBOSE:
	// Log.v(tag, msg+pos);
	// break;
	// case Log.WARN:
	// Log.w(tag, msg+pos);
	// break;
	// default:
	// Log.wtf("dbgUtil", "LOG TYPE ERROR!"+pos);
	// break;
	// }
	//
	// }

	private static String getTracePos()
	{
		// StackTraceElement[] elements =
		// Thread.currentThread().getStackTrace();
		StackTraceElement element = Thread.currentThread().getStackTrace()[4];

		return " at " + element.getClassName() + "." + element.getMethodName()
				+ "(" + element.getFileName() + ":" + element.getLineNumber()
				+ ")";
	}

	public static void dbgCursorInfo(Cursor cursor, Context context/*
																	 * , String
																	 * TracePos
																	 */)
	{
		// if (ENABLE_SQL_DEBUG == false)
		// return;

		// ----------------------debug cursor-----------------------------------
		Log.d("sql_dbg@dbgCursorInfo",
				getTracePos() + "Cursor size:	" + cursor.getCount()
						+ ";	columns count:	" + cursor.getColumnCount() + ";");
		// dbgUtil.Log(Log.DEBUG,"sql_dbg", getTracePos() + "Cursor size:	" +
		// cursor.getCount()
		// + ";	columns count:	" + cursor.getColumnCount() + ";");
		for (int i = 0; i < cursor.getColumnCount(); i++)
		{
			Log.d("sql_dbg@dbgCursorInfo", "column idx:	" + i
					+ ";		column name:	" + cursor.getColumnName(i) + ";");
			// dbgUtil.Log(Log.DEBUG,"sql_dbg",
			// "column idx:	" + i + ";		column name:	"
			// + cursor.getColumnName(i) + ";");
		}
		// ----------------------debug cursor-----------------------------------

	}
	// public static void dbgCursorMoreInfo(Cursor cursor /*, String TracePos*/)
	// {
	// if(Boolean.parseBoolean(context.getString(R.string.flag_debug))==false)
	// return;
	//
	//
	// //----------------------debug cursor-----------------------------------
	// dbgUtil.Log(Log.DEBUG,"sql_dbg",Log.getStackTraceString(new Throwable())
	// +"Cursor size:	"+cursor.getCount()
	// +";	columns count:	"+cursor.getColumnCount()
	// +";");
	// for (int i =0;i<cursor.getColumnCount();i++)
	// {
	// dbgUtil.Log(Log.DEBUG,"sql_dbg","column idx:	"+i
	// +";		column name:	"+cursor.getColumnName(i)
	// +";");
	// }
	// //----------------------debug cursor-----------------------------------
	//
	// }
}
