package com.example.mountaintravel.kind;

/**
 * 
 */

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Calendar;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;

public class MyCrashHandler implements UncaughtExceptionHandler {
	private static MyCrashHandler myCrashHandler;
	private Context context;
	private String mUser = "";
	private String mMac = "";
	private MyCrashHandler() {
	}
	public void init(Context context) {
		this.context = context;
	}
	public static synchronized MyCrashHandler getInstance() {
		if (myCrashHandler != null) {
			return myCrashHandler;
		} else {
			myCrashHandler = new MyCrashHandler();
			return myCrashHandler;
		}
	}

	public void uncaughtException(Thread arg0, Throwable arg1) {
		Log.e("", "enter uncaughtException");
		final String ver = getVersionInfo();
		final String errorinfo = getErrorInfo(arg1);

		File f = Environment.getExternalStorageDirectory();// 获取SD卡目录

		File fileDir = new File(f, "test.txt");

		FileOutputStream os;
		try {
			os = new FileOutputStream(fileDir);
			os.write(errorinfo.getBytes());
			os.close();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// System.exit(0);

	}

	public void WriteStringToFile2(String filePath, String errorinfo) {
		try {
			FileWriter fw = new FileWriter(filePath, true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.append(errorinfo);
			fw.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	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;
	}

	private String getVersionInfo() {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
			return info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "版本号未知";
	}

	public void setUserInfo(String user) {
		Log.e("AAAAAAAA", "setUser: " + user);
		mUser = user;
	}

	public void setDeviceInfo(String mac) {
		Log.e("AAAAAAAA", "setDevice: " + mac);
		mMac = mac;
	}
}