package com.gh.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.os.Process;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.gh.common.util.DataUtils;
import com.gh.common.util.Utils;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;

public class AppController extends Application {

	public static final String TAG = AppController.class.getSimpleName();
	// xiaomi push appid
	public static final String APP_ID = "2882303761517352993";
	// xiaomi push appkey
	public static final String APP_KEY = "5451735292993";

	private static AppController mInstance;
	private static ArrayMap<String, Object> objectMap = new ArrayMap<>();

	private RequestQueue mRequestQueue;

	private ArrayList<Activity> list = new ArrayList<>();

	private boolean isFinish = false;

	@Override
	public void onCreate() {
		super.onCreate();

//		File dexPath = new File(getDir("dex", Context.MODE_PRIVATE), "hackdex_dex.jar");
//		DexUtils.prepareAssetsDex(this, dexPath, "hackdex_dex.jar");
//		HotFix.patch(this, dexPath.getAbsolutePath(), "dodola.hackdex.AntilazyLoad");

//		SharedPreferences sp = this.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
//		File directory = new File(this.getFilesDir().getAbsolutePath() + File.separator +  "hotfix");
//		if (directory.exists()) {
//			File[] files = directory.listFiles();
//			for (File file : files) {
//                Utils.log("dex file = " + file.getName());
//                String clazz = sp.getString(file.getName(), null);
//                if (clazz != null) {
//                    dexPath = new File(getDir("dex", Context.MODE_PRIVATE), file.getName());
//                    DexUtils.prepareDex(this, dexPath, file);
//                    HotFix.patch(this, dexPath.getAbsolutePath(), clazz);
//                    Utils.log(file.getName() + " patch success");
//                }
//			}
//		}

		DataUtils.init(this);

		AppUncaHandler uncaHandler = new AppUncaHandler(this);
		Thread.setDefaultUncaughtExceptionHandler(uncaHandler);
		mInstance = this;

		// 注册push服务，注册成功后会向GHPushMessageReceiver发送广播
		// 可以从GHPushMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
		if (shouldInit()) {
			MiPushClient.registerPush(this, APP_ID, APP_KEY);
		}

		LoggerInterface newLogger = new LoggerInterface() {

			@Override
			public void setTag(String tag) {
				// ignore
			}

			@Override
			public void log(String content, Throwable t) {
				Log.d(TAG, content, t);
			}

			@Override
			public void log(String content) {
				Log.d(TAG, content);
			}
		};
		Logger.setLogger(this, newLogger);

	}

	public static void put(String key, Object object) {
		objectMap.put(key, object);
	}

	public static Object get(String key, boolean isRemove) {
		if (isRemove) {
			return objectMap.remove(key);
		} else {
			return objectMap.get(key);
		}
	}

	public static void remove(String key) {
		objectMap.remove(key);
	}

	/**
	 * Activity关闭时，删除Activity列表中的Activity对象
	 */
	public void removeActivity(Activity a) {
		if (!isFinish) {
			list.remove(a);
			Utils.log("remove = " + a.getClass().getSimpleName());
		}
	}

	/**
	 * 向Activity列表中添加Activity对象
	 */
	public void addActivity(Activity a) {
		Utils.log("add = " + a.getClass().getSimpleName());
		list.add(a);
	}

	/**
	 * 关闭Activity列表中的所有Activity
	 */
	public void finishActivity() {
		isFinish = true;
		for (int i = list.size() - 1; i >= 0; i--) {
			Activity activity = list.get(i);
			if (null != activity) {
				Utils.log("finish = " + activity.getClass().getSimpleName());
				activity.finish();
			}
		}
		// 杀死该应用进程
		Process.killProcess(Process.myPid());
	}

	public static String getProcessName(Context cxt, int pid) {
		ActivityManager am = (ActivityManager) cxt
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
		if (runningApps == null) {
			return null;
		}
		for (RunningAppProcessInfo procInfo : runningApps) {
			if (procInfo.pid == pid) {
				return procInfo.processName;
			}
		}
		return null;
	}

	public static synchronized AppController getInstance() {
		return mInstance;
	}

	public static <T> void addToRequestQueue(Request<T> request) {
		request.setTag(TAG);
		getInstance().addRequest(request);
	}

	public static <T> void addToRequestQueue(Request<T> request, String tag) {
		if (TextUtils.isEmpty(tag)) {
			tag = TAG;
		}
		request.setTag(tag);
		getInstance().addRequest(request);
	}

	public static void canclePendingRequests(String tag) {
		if (TextUtils.isEmpty(tag)) {
			tag = TAG;
		}
		getInstance().cancleRequest(tag);
	}

	public <T> void addRequest(Request<T> request) {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}
		mRequestQueue.add(request);
	}
	
	public void cancleRequest(Object tag){
		if (mRequestQueue != null) {
			mRequestQueue.cancelAll(tag);
		}
	}
	
	private boolean shouldInit() {
		ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
		List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
		String mainProcessName = getPackageName();
		Log.d(TAG, mainProcessName);
		int myPid = Process.myPid();
		for (RunningAppProcessInfo info : processInfos) {
			if (info.pid == myPid && mainProcessName.equals(info.processName)) {
				return true;
			}
		}
		return false;
	}

}
