package com.nova.brain.glass.common;

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

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

/*************************************************************************************************
 * <pre>
 * @包路径： cn.org.bjca.wcert.ywq.utils.crash
 *
 * @类描述:
 * @版本: V1.5.1
 * @作者 daizhenhong
 * @创建时间 2017/12/13 下午4:22
 *
 * @修改记录：
-----------------------------------------------------------------------------------------------
----------- 时间      |   修改人    |     修改的方法       |         修改描述   ---------------
-----------------------------------------------------------------------------------------------
</pre>
 ************************************************************************************************/
public class CrashHandler implements Thread.UncaughtExceptionHandler {


    private static String TAG = "CrashHandler";
    // 系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    // 用于格式化日期,作为日志文件名的一部分
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private static CrashHandler mCrashHandler;
    private Context mContext;


    private CrashHandler() {

    }

    public static CrashHandler getInstance() {
        if (mCrashHandler == null) {
            synchronized (CrashHandler.class) {
                mCrashHandler = new CrashHandler();
            }
        }
        return mCrashHandler;
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if (!handleException(throwable) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, throwable);
        } else {
            SystemClock.sleep(2000);
            // 退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }


    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        try {
            saveCrashInfoFile(ex);
            SystemClock.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    private String saveCrashInfoFile(Throwable ex) {
        StringBuffer sb = new StringBuffer();

        if (hasSdcard())
            try {
                SimpleDateFormat sDateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                String date = sDateFormat.format(new Date());
                sb.append("\r\n" + date + "\n");

                Writer writer = new StringWriter();
                PrintWriter printWriter = new PrintWriter(writer);
                ex.printStackTrace(printWriter);
                Throwable cause = ex.getCause();
                while (cause != null) {
                    cause.printStackTrace(printWriter);
                    cause = cause.getCause();
                }
                printWriter.flush();
                printWriter.close();
                String result = writer.toString();
                sb.append(result);

                String fileName = writeFile(sb.toString());
                return fileName;
            } catch (Exception e) {
                Log.e(TAG, "an error occured while writing file...", e);
                sb.append("an error occured while writing file...\r\n");
                writeFile(sb.toString());
            }
        return null;
    }

    private String writeFile(String text) {
        Log.e("writeFile", text);
        String time = formatter.format(new Date());
        String fileName = "crash-demo-" + time + ".log";

        String path = getGlobalpath();

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path + fileName, true);
            fos.write(text.getBytes());
            fos.flush();
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }


    public String getGlobalpath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "crash" + File.separator;
    }


    public boolean hasSdcard(){
        return Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);
    }
}

