package cc.winboll.studio.regexputils.develop;

/*
 * 应用日志类
 * 源码维护：ZhanGSKen@QQ.COM
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;

public class LogUtils {

    public static final String TAG = "BaseApplication";

    static SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");

    public static void d(String szTAG, String szMessage) {
        saveLog(szTAG, szMessage);
    }

    static void saveLog(String szTAG, String szMessage) {
        try {
            File fLog = new File(WinBollBase._mszLogFilePath);
            //FileWriter fw = new FileWriter(fLog, Charset.defaultCharset(), true);
            //fw.append(mSimpleDateFormat.format(System.currentTimeMillis()) + "[" + szTAG + "]: " + szMessage + "\n");
            //fw.close();
            BufferedWriter out = null;
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fLog, true), "UTF-8"));
            out.write(mSimpleDateFormat.format(System.currentTimeMillis()) + "[" + szTAG + "]: " + szMessage + "\n");
            out.close();

        } catch (IOException e) {
            LogUtils.d(TAG, "IOException : " + e.getMessage());
        }
    }

    public static String loadLog() {
        File fLog = new File(WinBollBase._mszLogFilePath);
        StringBuffer sb = new StringBuffer();
        try {
            //FileInputStream fileInputStream = new FileInputStream(fLog);
            //int size = fileInputStream.available();
            //for (int i = 0; i < size; i++) {
            //    sb.append((char) fileInputStream.read());
            //}
            BufferedReader in = null;
            in = new BufferedReader(new InputStreamReader(new FileInputStream(fLog), "UTF-8"));
            String line = "";
            while ((line = in.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }

        } catch (IOException e) {
            LogUtils.d(TAG, "IOException : " + e.getMessage());
        } 
        return sb.toString();
    }

    public static void cleanLog() {
        File fLog = new File(WinBollBase._mszLogFilePath);
        if (fLog.exists()) {
            fLog.delete();
        }
    }

}
