package com.ivrjack.ru01.demo;

import android.app.Application;
import android.util.Log;

import com.ivrjack.ru01.test.TestMail;
import com.ivrjack.ru01.test.TestObjects;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by ChenRong02 on 2016/4/12 0012.
 */
public class DemoApplication extends Application {

    private Thread.UncaughtExceptionHandler defaultHandler;

    private int version = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                Thread.setDefaultUncaughtExceptionHandler(defaultHandler);
                final StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                ex.printStackTrace(pw);
                Log.e("demo", ex.getMessage());
                Log.e("demo", sw.toString());

                Thread thread1 = new Thread() {
                    @Override
                    public void run() {
                        try {
                            TestObjects testObjects = new TestObjects(DemoApplication.this);
                            testObjects.exception = sw.toString();
                            TestMail testMail = new TestMail();
                            testMail.sendTestReport(testObjects);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread1.start();
                try {
                    thread1.join();
                } catch (InterruptedException ignore) {
                }
                defaultHandler.uncaughtException(thread, ex);
            }
        });
    }

    public int getVersion(){
        return version;
    }

    public void setVersion(int version){
        this.version = version;
    }
}
