package com.gh.base;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.gh.common.util.FileUtils;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.tencent.stat.StatService;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class AppUncaHandler implements UncaughtExceptionHandler {

	private UncaughtExceptionHandler mDefaultHandler;
	private AppController appController;

	public AppUncaHandler(AppController appController) {
		// 获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		this.appController = appController;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else {
			new Thread() {
				@Override
				public void run() {
					Looper.prepare();
					Toast.makeText(appController.getApplicationContext(),
							"\"光环助手\"发生错误", Toast.LENGTH_SHORT).show();
					Looper.loop();
				}
			}.start();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			Intent intent = new Intent(appController.getApplicationContext(),
					SplashScreenActivity.class);
			intent.setAction(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			PendingIntent restartIntent = PendingIntent.getActivity(
					appController.getApplicationContext(), 0, intent,
					Intent.FLAG_ACTIVITY_NEW_TASK);
			// 退出程序并重启
			AlarmManager mgr = (AlarmManager) appController
					.getSystemService(Context.ALARM_SERVICE);
			mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
					restartIntent); // 1秒钟后重启应用
			appController.finishActivity();
		}
	}

	// 保存log到本地
	private void saveLog(Throwable ex) {
		String errorMsg = Log.getStackTraceString(ex);

		// MTA主动上传错误
		StatService.reportError(appController.getApplicationContext(), errorMsg);

		Map<String, Object> map = new HashMap<>();
		map.put("content", errorMsg);
		map.put("type", android.os.Build.MODEL);
		map.put("system", android.os.Build.VERSION.SDK_INT + "="
				+ android.os.Build.VERSION.RELEASE);
		DataCollectionManager.onEvent(appController.getApplicationContext(),
				"error", map, false);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",
				Locale.getDefault());
		File file = new File(FileUtils.getLogPath(
				appController.getApplicationContext(),
				format.format(new Date()) + "_gh_assist" + ".log"));
		FileWriter writer = null;
		try {
			file.createNewFile();
			writer = new FileWriter(file);
			writer.write(errorMsg);
			writer.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

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