package com.baidu.ai.sample.util;

import android.content.Context;

import com.baidu.ai.sample.data.ContextConstant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CrashUtil {

    private Thread.UncaughtExceptionHandler oldExceptionHandler;

    public CrashUtil() {
    }

    public void initCrashHandler() {
        Thread.UncaughtExceptionHandler currentExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        if (currentExceptionHandler != null) {
            oldExceptionHandler = currentExceptionHandler;
        }
        Thread.setDefaultUncaughtExceptionHandler(new MUnCaughtExceptionHandler());
    }

    private class MUnCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            writeLocal(t, e);

            if (oldExceptionHandler != null) {
                oldExceptionHandler.uncaughtException(t, e);
            }
        }
    }

    private void writeLocal(Thread t, Throwable e) {
        StringWriter writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        Throwable cause = e.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.flush();
        printWriter.close();
        String result = writer.toString();
        writeFile(result);
    }


    private void writeFile(String sb) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String time = formatter.format(new Date());
        File folder = getCrashFile(ContextConstant.getContext());
        String filePath = folder.getAbsolutePath() + File.separator + "crash-" + time + ".log";

        try {
            FileOutputStream fos = new FileOutputStream(filePath, true);
            fos.write(sb.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File getCrashFile(Context context) {
        File rootDir = null;
        if (FileUtils.isSDMounted()) {
            rootDir = context.getApplicationContext().getExternalFilesDir(null);
        }
        File dir = new File(rootDir, "crash");

        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

}
