package com.gingersoft.gsa.cloud.base.utils.crash;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.telecom.Call;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.base.utils.other.AppUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AppCrashHandler implements UncaughtExceptionHandler {
    /**
     * Debug Log tag
     */
    public static final String TAG = "AppCrashHandler";
    /**
     * 是否开启日志输出,在Debug状态下开启,
     * 在Release状态下关闭以提示程序性能
     */
    public static final boolean DEBUG = true;
    /**
     * 系统默认的UncaughtException处理类
     */
    private UncaughtExceptionHandler mDefaultHandler;
    /**
     * CrashHandler实例
     */
    private static AppCrashHandler INSTANCE;
    /**
     * 程序的Context对象
     */
    private Context mContext;
    /**
     * 出错的提示串头
     **/
    private String ErrorStr = "發生錯誤, 請聯絡支援人員!";
    /**
     * 使用Properties来保存设备的信息和错误堆栈信息
     */
    private static final String VERSION_NAME = "versionName";
    private static final String VERSION_CODE = "versionCode";
    private static final String STACK_TRACE = "STACK_TRACE";
    /**
     * 错误报告文件的扩展名
     */
    private static final String CRASH_REPORTER_EXTENSION = ".cyposdebug";
    private String machinename;
    private String crashFile;

    private File f;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");// 用于格式化日期,作为日志文件名的一部分
    private Map<String, String> info = new HashMap<String, String>();// 用来存储设备信息和异常信息

    /**
     * 保证只有一个CrashHandler实例
     */
    private AppCrashHandler() {
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static AppCrashHandler getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new AppCrashHandler();
        }
        return INSTANCE;
    }

    /**
     * 初始化,注册Context对象,
     * 获取系统默认的UncaughtException处理器,
     * 设置该CrashHandler为程序的默认处理器
     *
     * @param ctx
     */
    public void init(Context ctx, String machinename) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.machinename = machinename;

        crashFile = ctx.getFilesDir().getAbsoluteFile().getParent() + File.separator + "shared_prefs" + File.separator + "Crash.xml";
        f = new File(crashFile);
        if (f.exists()) {
            sendPreviousReportsToServer();
            f.delete();
        }
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            //Sleep一会后结束程序
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error : ", e);
            }
            appExit(mContext);
        }
    }

    /**
     * 退出应用程序
     */
    public static void appExit(Context context) {
//        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(context);
//        List<Activity> activityList = appComponent.appManager().getActivityList();
//        try {
//            for (int i = 0; i < activityList.size(); i++) {
//                activityList.get(i).finish();
//                activityList.remove(i);
//            }
//            if (appComponent.appManager().activityClassIsLive(MainActivity.class)) {
//                appComponent.appManager().findActivity(MainActivity.class).finish();
//            }
//            if (appComponent.appManager().activityClassIsLive(TableServiceActivity.class)) {
//                appComponent.appManager().findActivity(TableServiceActivity.class).finish();
//            }
//            // 退出程序
//            android.os.Process.killProcess(android.os.Process.myPid());
//            /**
//             * finish()是Activity的类方法，仅仅针对Activity，当调用finish()时，只是将活动推向后台，并没有立即释放内存，
//             * 活动的资源并没有被清理；当调用System.exit(0)时，退出当前Activity并释放资源（内存），
//             * 但是该方法不可以结束整个App如有多个Activty或者有其他组件service等不会结束。
//             * 0表示正常退出,1表示非正常 。
//             */
//            System.exit(1);
//        } catch (Exception e) {
//        }
    }

    /**
     * 自定义错误处理,收集错误信息
     * 发送错误报告等操作均在此完成.
     * 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, ErrorStr, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        // 获取跟踪的栈信息，除了系统栈信息，还把手机型号、系统版本、编译版本的唯一标示
        StackTraceElement[] trace = ex.getStackTrace();
        StackTraceElement[] trace2 = new StackTraceElement[trace.length + 5];
        System.arraycopy(trace, 0, trace2, 0, trace.length);
        trace2[trace.length + 0] = new StackTraceElement("Android", "MODEL", Build.MODEL, -1);
        trace2[trace.length + 1] = new StackTraceElement("Android", "VERSION", Build.VERSION.RELEASE, -1);
        trace2[trace.length + 2] = new StackTraceElement("GSA-SUPER", "APP_VERSION_CODE", AppUtils.getVerCode(mContext) + "", -1);
        trace2[trace.length + 3] = new StackTraceElement("GSA-SUPER", "APP_VERSION_NAME", AppUtils.getVerName(mContext), -1);
        trace2[trace.length + 4] = new StackTraceElement("Android", "FINGERPRINT", Build.FINGERPRINT, -1);
        // 追加信息，因为后面会回调默认的处理方法
        ex.setStackTrace(trace2);
        ex.printStackTrace(printWriter);
        // 把上面获取的堆栈信息转为字符串，打印出来
        String stacktrace = result.toString();
        printWriter.close();
        LogUtil.d(TAG,stacktrace);

        //收集设备信息
        collectCrashDeviceInfo(mContext);
        //保存错误报告到SP
        saveCrashInfoToSP(ex);
        //保存错误报告到文件
        saveCrashInfo2File(ex);
        //发送错误报告到服务器
        sendCrashReportsToServer(mContext);
        return true;
    }

    /**
     * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告
     */
    public void sendPreviousReportsToServer() {
        sendCrashReportsToServer(mContext);
    }

    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     *
     * @param ctx
     */
    private void sendCrashReportsToServer(Context ctx) {
//        uploadFile2Svr(crashFile, "ErrorAppCrash_" + TimeUtil.StampToData(TimeUtil.dateFormatYMDHMS_f, System.currentTimeMillis()));
    }

    public void showServerice(String image, String pictureName, int tag) {

//        String url1 = GSAApplication.getWebServerAddress() + "/App_Crash";
//
//        StringBuilder tempParams = new StringBuilder();
//        try {
//            tempParams.append(String.format("%s=%s", "APP_VERSION_NAME", URLEncoder.encode(DeviceUtils.getVersionName(mContext), "utf-8")));
//            tempParams.append(String.format("%s=%s", "APP_VERSION_CODE", URLEncoder.encode(String.valueOf(DeviceUtils.getVersionCode(mContext)), "utf-8")));
//            tempParams.append(String.format("%s=%s", "VERSION", URLEncoder.encode(Build.VERSION.RELEASE, "utf-8")));
//            tempParams.append(String.format("%s=%s", "MODEL", URLEncoder.encode(Build.MODEL, "utf-8")));
//
//            tempParams.append(String.format("%s=%s", "filename", URLEncoder.encode(pictureName + ".xml", "utf-8")));
//            tempParams.append(String.format("&%s=%s", "image", URLEncoder.encode(image, "utf-8")));
//            tempParams.append(String.format("&%s=%s", "tag", URLEncoder.encode(String.valueOf(tag), "utf-8")));
//            tempParams.append(String.format("&%s=%s", "machinename", URLEncoder.encode(machinename, "utf-8")));
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
//
//        new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//                String requestUrl = String.format("%s?%s", url1, tempParams.toString());
//                OkHttpClient client = new OkHttpClient.Builder()
//                        .connectTimeout(GSAApplication.REQUEST_TIMEOUT, TimeUnit.SECONDS)
//                        .readTimeout(GSAApplication.REQUEST_TIMEOUT, TimeUnit.SECONDS)
//                        .build();
//
//                Request request = new Request.Builder().url(requestUrl).build();
//                Call call = client.newCall(request);
//                try {
//                    Response response = call.execute();
//                    if (response.isSuccessful()) {
//                        String str = response.body().string();
//
//                    } else {
//                        throw new IOException("Unexpected code " + response);
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }

    private void uploadFile2Svr(String pictureFile, String pictureName) {
        try {
            FileInputStream fis = new FileInputStream(pictureFile);
            //ByteArrayOutputStream baos=new ByteArrayOutputStream();
            byte[] buffer = new byte[100 * 1024];
            int count = 0;
            int i = 0;
            while ((count = fis.read(buffer)) >= 0) {
                String uploadBuffer = new String(Base64.encode(buffer, 0, count, Base64.DEFAULT));
                showServerice(uploadBuffer, pictureName, i);
                for (int j = 0; j < 1000; j++) ;
                i++;
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取错误报告文件名
     *
     * @param ctx
     * @return
     */
    private String[] getCrashReportFiles(Context ctx) {
        File filesDir = ctx.getFilesDir();
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(CRASH_REPORTER_EXTENSION);
            }
        };
        return filesDir.list(filter);
    }

    /**
     * 保存一些信息到文件中
     */
    public void saveInfoToFile(String w1, String writeValue) {
        Writer info = new StringWriter();
//        mSetup.setSaveValue_Crash(w1, writeValue, mContext);
    }

    /**
     * 收集程序崩溃的设备信息
     *
     * @param ctx
     */
    public void collectCrashDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "no set" : pi.versionName;
                String versionCode = pi.versionCode + "";
                info.put("versionName", versionName);
                info.put("versionCode", versionCode);
//                mSetup.setSaveValue_Crash(VERSION_NAME, versionName, mContext);
//                mSetup.setSaveValue_Crash(VERSION_CODE, versionCode, mContext);
            }
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Error while collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                info.put(field.getName(), field.get("").toString());
//                mSetup.setSaveValue_Crash(field.getName(), String.valueOf(field.get(null)), mContext);
                if (DEBUG) {
                    Log.d(TAG, field.getName() + " : " + field.get(null));
                }
            } catch (Exception e) {
                Log.e(TAG, "Error while collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到SP
     *
     * @param ex
     * @return
     */
    private String saveCrashInfoToSP(Throwable ex) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        String result = info.toString();
        printWriter.close();

//        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(mContext);
//        mSetup.setSaveValue_Crash("Error-Activity", appComponent.appManager().getTopActivity().getClass().getName().toString(), mContext);
//        mSetup.setSaveValue_Crash("Error:", result, mContext);
//        long timestamp = System.currentTimeMillis();
//        mSetup.setSaveValue_Crash("Error-time:", format.format(timestamp) + "", mContext);
        return null;
    }

    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : info.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\r\n");
        }
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        ex.printStackTrace(pw);
        Throwable cause = ex.getCause();
        // 循环着把所有的异常信息写入writer中
        while (cause != null) {
            cause.printStackTrace(pw);
            cause = cause.getCause();
        }
        pw.close();// 记得关闭
        String result = writer.toString();
        sb.append(result);
        // 保存文件
        long timetamp = System.currentTimeMillis();
        String time = format.format(new Date());
//        String fileName = "crash-" + GSAApplication.machineName + "-" + DeviceUtils.getVersionName(GSAApplication.getAppContext()) + "-" + time + "-" + timetamp + "-" + info.get("versionName") + ".xml";
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//外部存储卡
//            try {
//                File dir = new File(FileUtils.ERRORLOG_PATH);
//                Log.i("CrashHandler", dir.toString());
//                //不存在就創建目錄
//                if (!dir.exists())
//                    dir.mkdirs();
//                FileOutputStream fos = new FileOutputStream(new File(FileUtils.ERRORLOG_PATH, fileName));
//                fos.write(sb.toString().getBytes());
//                fos.close();
//                return fileName;
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        return null;
    }

    public void setErrorStr(String ErrorStr) {
        this.ErrorStr = ErrorStr;
    }
}
