package com.imofan.android.basic;

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 魔方Crash异常处理类
 */
class MFCrashHandler implements Thread.UncaughtExceptionHandler {
    private final static String LOG_TAG = Mofang.LOG_TAG + "_MFCrashHandler";
    private static MFCrashHandler self;
    private MFDatabaseManager dbManager;

    private MFCrashHandler(MFDatabaseManager dbManager) {
        this.dbManager = dbManager;
    }

    synchronized static void init(MFDatabaseManager dbManager) {
        if(self == null) {
            self = new MFCrashHandler(dbManager);
            Thread.setDefaultUncaughtExceptionHandler(self);
        }
    }

    public void uncaughtException(Thread thread, Throwable throwable) {
        Log.e(LOG_TAG, "[uncaughtException]Find uncaught exception");
        throwable.printStackTrace();
        JSONObject exceptionJson = new JSONObject();
        try {
            exceptionJson.put("name", throwable.toString());
            exceptionJson.put("stack", Log.getStackTraceString(throwable));
//            String stack = throwable.toString() + "\\|\\" + Log.getStackTraceString(throwable);
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat hourFormat = new SimpleDateFormat("H");
            MFStatEvent.addEvent(dbManager, MFStatEvent.EVENT_CRASH, Integer.parseInt(dateFormat.format(now)),
                    Integer.parseInt(hourFormat.format(now)), exceptionJson.toString());
        } catch (JSONException e) {

        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
