/**
 * Cobub Razor
 * <p>
 * An open source analytics android sdk for mobile applications
 *
 * @package Cobub Razor
 * @author WBTECH Dev Team
 * @copyright Copyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd.
 * @license http://www.cobub.com/products/cobub-razor/license
 * @link http://www.cobub.com/products/cobub-razor/
 * @filesource
 * @since Version 0.1
 */
package com.oo.seex.oo_statistics_lib.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.oo.seex.oo_statistics_lib.bean.ErrorStaBean;
import com.oo.seex.oo_statistics_lib.bean.StatistivsBean;
import com.oo.seex.oo_statistics_lib.constant.OOConstant;
import com.oo.seex.oo_statistics_lib.getjsonobject.GetJson;
import com.oo.seex.oo_statistics_lib.network.NetworkUitlity;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 抓取异常并且发送到服务器的操作；在接受到hanler的消息后开始运行
 */
public class MyCrashHandler implements UncaughtExceptionHandler {
    private static MyCrashHandler myCrashHandler;
    private Context context;
    private String stacktrace;
    private String activities;
    private long time;
    private String appkey;
    private String os_version;

    public Handler handler = null;

    private MyCrashHandler() {

    }

    public static synchronized MyCrashHandler getInstance() {
        if (myCrashHandler != null) {
            return myCrashHandler;
        } else {
            myCrashHandler = new MyCrashHandler();
            return myCrashHandler;
        }
    }

    public void init(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
    }

    /**
     * 发送错误信息到服务器 实时
     *
     * @param thread
     * @param arg1
     */
    @Override
    public void uncaughtException(Thread thread, final Throwable arg1) {

        arg1.printStackTrace();

        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Looper.prepare();
                    String errorinfo = getErrorInfo(arg1);

                    String[] ss = errorinfo.split("\n\t");
                    String headstring = ss[0] + "\n\t" + ss[1] + "\n\t" + ss[2];

                    if (headstring.length() > 255) {
                        headstring = headstring.substring(0, 255) + "\n\t";
                    } else {
                        headstring = headstring + "\n\t";
                    }

                    String newErrorInfoString = headstring + errorinfo;

                    stacktrace = newErrorInfoString;
                    activities = CommonUtil.getActivityName(context);
                    time = CommonUtil.getTime();
                    appkey = CommonUtil.getAppKey(context);
                    os_version = CommonUtil.getOSVersion(context);

                    ErrorStaBean errorInfo = getErrorData(context);

                    final StatistivsBean statistivsBean = new StatistivsBean();
                    statistivsBean.setErrorInfo(errorInfo);

                    if (CommonUtil.isNetworkAvailable(context)) {
                        if (!stacktrace.equals("")) {
                            NetworkUitlity.getInstance().requestPost(OOConstant.preUrl + OOConstant.errorUrl,
                                    GetJson.getErrorInfoParams(errorInfo), context, new NetworkUitlity.NetListener() {
                                        @Override
                                        public void succee() {
                                        }

                                        @Override
                                        public void error() {
                                            if (handler != null) {
                                                CommonUtil.saveInfoToFile(handler, "errorInfo", statistivsBean, context);
                                            }
                                        }
                                    });
                        }
                    } else {
                        if (handler != null) {
                            CommonUtil.saveInfoToFile(handler, "errorInfo", statistivsBean, context);
                        }
                    }
                    android.os.Process.killProcess(android.os.Process.myPid());
                    Looper.loop();
                } catch (Exception e) {
                    CommonUtil.printLog(e);
                }
            }
        }.start();

    }

    /**
     * 组拼成JsonObject对象
     *
     * @param context
     * @return
     */
    private ErrorStaBean getErrorData(Context context) {

        ErrorStaBean errorStaBean = new ErrorStaBean();

        errorStaBean.setStacktrace(stacktrace);
        errorStaBean.setTime(String.valueOf(time));
        errorStaBean.setActivity(activities);
        errorStaBean.setAppkey(appkey);

        errorStaBean.setChannel(CommonUtil.getChannel(context));

        errorStaBean.setVersion(CommonUtil.getVersion(context));
        errorStaBean.setOs_version(os_version);

        errorStaBean.setUserId(CommonUtil.getUserIdentifier(context));
        errorStaBean.setDevice_id(CommonUtil.getDeviceID(context));

        return errorStaBean;
    }

    /**
     * 获取错误日志信息
     *
     * @param arg1
     * @return
     */
    private String getErrorInfo(Throwable arg1) {
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        arg1.printStackTrace(pw);
        pw.close();
        String error = writer.toString();
        return error;
    }

}
