package com.tsgame.tsgame_niuniu.system;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.game.webgame.view.SpUtil;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
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.util.Log;

public class CrashHandler implements UncaughtExceptionHandler{
	private static final String TAG = "CrashHandler";
	private static final boolean DEBUG = true;
	
	private static  String PATH = Environment.getExternalStorageDirectory().getPath() + "/CrashTest/log/";//Environment.getExternalStorageDirectory().getPath()
	private static final String FILE_NAME = "crash";
	private static final String FILE_NAME_SUFFIX = ".txt";
	
	private static CrashHandler sInstance = new CrashHandler();
	private static UncaughtExceptionHandler mDefaultCrashHandler;
	private Context mContext;
	SharedPreferences share;
	
	public CrashHandler() {
		// TODO Auto-generated constructor stub
	}
	
	public static CrashHandler getInstance(){
		return sInstance;
	}
	
	public void init(Context context){
		mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
		mContext = context.getApplicationContext();
		share=SpUtil.getSharePerference(context);
		
	}
	
	//有未被捕获的异常的时候，系统就自动调用这个方法
	@Override
	public void uncaughtException(Thread thread, final Throwable ex) {
		
		
		
//		new Thread() {
//			public void run() {
//				Looper.prepare();
//				new AlertDialog.Builder(mContext).setTitle("提示")
//						.setCancelable(false).setMessage("抱歉,程序无响应,请重新打开")
//						.setNeutralButton("确定",new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//								// TODO Auto-generated method stub
//								ex.printStackTrace();
//								System.exit(0);  
//							}
//						}).create().show();
//				Looper.loop();
//			};
//
//		}.start();
		
		Log.w(TAG, "uncaughtException:"+ex.getMessage()+","+PATH);
		
		try {
			dumpExceptionToSDCard(ex);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ex.printStackTrace();
		if(mDefaultCrashHandler != null){
			mDefaultCrashHandler.uncaughtException(thread, ex);
		}else{
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}
	
	private void dumpExceptionToSDCard(Throwable ex) throws IOException{
		if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			if(DEBUG){
				Log.w(TAG, "sdcard unmounted, skip dump exception");
				return;
			}
		}
		File dir=  new File(PATH);
		if(!dir.exists()){
			dir.mkdirs();
		}
		long current = System.currentTimeMillis();
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
		String filename="love"+PATH+FILE_NAME + time + FILE_NAME_SUFFIX;
		
		
		
		
		File file = new File(filename);
		SpUtil.setStringSharedPerference(share, "bugfilename",filename);
		try {
			PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
			pw.println(time);
			dumpPhoneInfo(pw);
			pw.println();
			ex.printStackTrace(pw);
			pw.close();
		} catch (NameNotFoundException e) {
			Log.e(TAG, "dump crash info failed");
		}
		
		
	}
	
	private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException{
		PackageManager pm = mContext.getPackageManager();
		PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
		pw.print("App Version: ");
		pw.print(pi.versionName);
		pw.print('_');
		pw.println(pi.versionCode);
		
		//Android版本号
		pw.print("OS Version");
		pw.print(Build.VERSION.RELEASE);
		pw.print("_");
		pw.println(Build.VERSION.SDK_INT);
		
		//手机制造商
		pw.print("Vendor: ");
		pw.println(Build.MODEL);
		
		//CPU架构
		pw.print("CPU ABI: ");
		pw.println(Build.CPU_ABI);
	}

}
