package com.imofan.android.pns;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Rex
 * Date: 12-9-7
 * Time: 下午9:17
 * To change this template use File | Settings | File Templates.
 */
public class PNLog {
    private final static String LOG_TAG = "Mofang_basic_MFLog";
    private static File logFile;

    public static void init(Context context) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        File logDir = new File(Environment.getExternalStorageDirectory(), "log");
        if(!logDir.exists() || logDir.isFile()) {
            logDir.mkdirs();
        }
        logFile = new File(logDir, "mofang." + dateFormat.format(new Date()));
    }

    public static void d(String tag, String message) {
        if(!PNService.debug) {
            return;
        }
        try{
            Log.d(tag, message);
            recode(message);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void e(String tag, String message) {
        try{
            Log.e(tag, message);
            recode(message);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void i(String tag, String message) {
        if(!PNService.debug) {
            return;
        }
        try{
            Log.i(tag, message);
            recode(message);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void w(String tag, String message) {
        try{
            Log.w(tag, message);
            recode(message);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    private static void recode(String message) {
        if(logFile != null) {
            try {
                if(!logFile.exists()){
                    Log.d(LOG_TAG, "logFile = " + logFile.getAbsolutePath());
                    logFile.createNewFile();
                }

                FileOutputStream outputStream = new FileOutputStream(logFile, true);
                outputStream.write((getCurrentTime() + ": " + message + "\r\n").getBytes());
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static String getCurrentTime(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(new Date());
    }
}
