package com.android.common.utils;

import android.os.Environment;
import android.os.Process;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogHelper {

    private static FileLog logToFile;

    private static boolean enableDefaultLog = true;

    private static boolean enableFileLog = true;
    
    private static final int RETURN_NOLOG = 99;

    static {
        try {
            if (enableFileLog)
                logToFile = new FileLog();
        } catch (RuntimeException e) {
            Log.e("LogHelper", e.toString());
        } catch (IOException e) {
            Log.e("LogHelper", e.toString());
        }
    }

    public static void setLogEnable(boolean enableDefaultLog) {
        LogHelper.enableDefaultLog = enableDefaultLog;
    }

    public static int d(String tag, String msg, Throwable tr) {

        if (msg == null)
            msg = "";

//        dfile(tag, msg);
        return enableDefaultLog ? Log.d(tag, msg, tr) : RETURN_NOLOG;
    }

    public static int d(String tag, String msg) {

        if (msg == null)
            msg = "";

//        dfile(tag, msg);
        return enableDefaultLog ? Log.d(tag, msg) : RETURN_NOLOG;
    }

    public static int e(String tag, String msg) {
        if (msg == null)
            msg = "";

//        efile(tag, msg);
        return enableDefaultLog ? Log.e(tag, "Pid = " + Process.myPid() + "," + msg) : RETURN_NOLOG;
    }

    public static int e(String tag, String msg, Throwable tr) {
        if (msg == null)
            msg = "";

        efile(tag, msg);
        return enableDefaultLog ? Log.e(tag, msg, tr) : RETURN_NOLOG;
    }

    public static int i(String tag, String msg, Throwable tr) {
        if (msg == null)
            msg = "";

        return enableDefaultLog ? Log.i(tag, msg, tr) : RETURN_NOLOG;
    }

    public static int i(String tag, String msg) {
        if (msg == null)
            msg = "";
        return enableDefaultLog ? Log.i(tag, msg) : RETURN_NOLOG;
    }


    public static int v(String tag, String msg, Throwable tr) {
        // vfile(tag, msg);
        return enableDefaultLog ? Log.v(tag, msg, tr) : RETURN_NOLOG;
    }

    public static int v(String tag, String msg) {
        // vfile(tag, msg);
        return enableDefaultLog ? Log.v(tag, msg) : RETURN_NOLOG;
    }

    public static int w(String tag, String msg) {
        return enableDefaultLog ? Log.w(tag, msg) : RETURN_NOLOG;
    }

    public static int w(String tag, Throwable tr) {
        return enableDefaultLog ? Log.w(tag, tr) : RETURN_NOLOG;
    }

    public static int w(String tag, String msg, Throwable tr) {
        return enableDefaultLog ? Log.w(tag, msg, tr) : RETURN_NOLOG;
    }

    public static void efile(String tag, String msg) {

        if (logToFile != null && enableFileLog) {
            logToFile.writeFileLog(Log.ERROR, tag, msg);
        }
    }

    public static void dfile(String tag, String msg) {
        d(tag,msg);
        if (logToFile != null && enableFileLog) {
            logToFile.writeFileLog(Log.DEBUG, tag, msg);
        }
    }

}

class FileLog {

    private static final String TAG = "LogHelper";

    private static final String SD_CARD = Environment.getExternalStorageDirectory()
            .getAbsolutePath();

    private final static String LOG_PATH = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/paiai/logs/";

    public static final int MAX_FILE_SIZE = 4; // M

    private FileWriter fileWriter;

    public FileLog() throws RuntimeException, IOException {
        File sdcard = new File(SD_CARD);
        String fileName = "paiai-"+new SimpleDateFormat("MM-dd-HH-mm").format(new Date()) + ".log";
        File logFile = new File(LOG_PATH+fileName);

        if (!sdcard.exists()) {
            throw new RuntimeException("SD card not exists!");
        } else {
            File dir = new File(LOG_PATH);
            dir.mkdirs();
            if (!logFile.exists()) {

                if (!logFile.createNewFile()) {
                    Log.e(TAG, "Create new file failed.");
                }

            } else {
                long fileSize = (logFile.length() >>> 20);// convert to M bytes
                if (fileSize > MAX_FILE_SIZE) {
                    try {
                        logFile.createNewFile();
                    } catch (IOException e) {
                        LogHelper.e(TAG, e.getMessage());
                    }
                }
            }
            fileWriter = new FileWriter(logFile, true);
        }
    }

    // we use one space to separate elements
    public void writeFileLog(int priority, String tag, String message) {

        Date date = new Date();
        SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy:MM:dd kk:mm:ss");
        String strLog = simpleDateFormate.format(date);

        StringBuffer sb = new StringBuffer(strLog);
        sb.append(' ');
        sb.append(strPriority[priority]);
        sb.append(' ');
        sb.append(tag);
        sb.append(' ');
        sb.append(message);
        sb.append('\n');
        strLog = sb.toString();

        try {
            fileWriter.write(strLog);
            fileWriter.flush();
        } catch (IOException e) {
            Log.e("FileLog", "", e);
        }
    }

    private static String strPriority[];
    static {
        strPriority = new String[8];
        strPriority[0] = "";
        strPriority[1] = "";
        strPriority[2] = "verbose";
        strPriority[3] = "debug";
        strPriority[4] = "info";
        strPriority[5] = "warn";
        strPriority[6] = "error";
        strPriority[7] = "ASSERT";
    }
}
