package com.gh.gamecenter.receiver;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import com.gh.common.util.RunningUtils;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.eventbus.EBMiPush;

import java.util.List;

import de.greenrobot.event.EventBus;

public class UninstallReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		
		String path = intent.getStringExtra("path");
		if (RunningUtils.isRunning(context)) {
			if (RunningUtils.isEqualsTop(context,
					DownloadManagerActivity.class.getName())) {
				ActivityManager manager = (ActivityManager) context
						.getSystemService(Context.ACTIVITY_SERVICE);
				List<RunningTaskInfo> task_info = manager.getRunningTasks(20);
				String packageName = context.getPackageName();
				for (int i = 0; i < task_info.size(); i++) {
					if (packageName.equals(task_info.get(i).topActivity
							.getPackageName())) {
						String className = task_info.get(i).topActivity
								.getClassName();
						// 这里是指从后台返回到前台 前两个的是关键
						Intent intent2 = new Intent();
						intent2.setAction(Intent.ACTION_MAIN);
						intent2.addCategory(Intent.CATEGORY_LAUNCHER);
						try {
							intent2.setComponent(new ComponentName(context,
									Class.forName(className)));
						} catch (ClassNotFoundException e) {
							
							e.printStackTrace();
						}
						// intent2.setClass(context, Class.forName(className));
						intent2.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
								| Intent.FLAG_ACTIVITY_NEW_TASK
								| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
						context.startActivity(intent2);
					}
				}
				EventBus.getDefault().post(new EBMiPush("plugin_install", path));
			} else {
				Intent intent2 = new Intent(context,
						DownloadManagerActivity.class);
				intent2.putExtra("currentItem", 0);
				intent2.putExtra("path", path);
				intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent2);
			}

		} else {
			// 应用未在运行
			Intent intent2 = new Intent(context, SplashScreenActivity.class);
			intent2.setAction(Intent.ACTION_MAIN);
			intent2.addCategory(Intent.CATEGORY_LAUNCHER);
			intent2.putExtra("from", "plugin_install");
			intent2.putExtra("path", path);
			intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent2);
		}
	}

}
