package com.gh.gamecenter.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.support.v4.util.ArrayMap;

import com.gh.base.AppController;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.RunningUtils;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBMiPush;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import de.greenrobot.event.EventBus;

/**
 * 用于接收点击小米推送的notification的广播
 * 
 * @author LGT
 * 
 */
public class NotificationReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			JSONObject jsonObject = new JSONObject(
					intent.getStringExtra("notifyData"));
			int id = intent.getIntExtra("notifyId", 0);
			switch (id) {
			case 0:
				if (RunningUtils.isRunning(context)) {
					// 应用正在运行,前台或后台
					Intent intent1 = new Intent(context, NewsDetailActivity.class);
					intent1.putExtra("id", jsonObject.get("_id").toString());
					intent1.putExtra("title", jsonObject.get("title").toString());
					intent1.putExtra("entrance", "小米推送");
					intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent1);
				} else {
					// 应用未在运行
					Intent intent1 = new Intent(context, SplashScreenActivity.class);
					intent1.setAction(Intent.ACTION_MAIN);
					intent1.addCategory(Intent.CATEGORY_LAUNCHER);
					intent1.putExtra("from", "mipush_news");
					intent1.putExtra("id", jsonObject.get("_id").toString());
					intent1.putExtra("title", jsonObject.get("title").toString());
					intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent1);
				}
				break;
			case 1:
				if (RunningUtils.isRunning(context)) {
					// 应用正在运行,前台或后台
					JSONArray jsonArray = jsonObject.getJSONArray("apk");
					ArrayMap<String, Boolean> map = getInstalledMapFromLocal(context);
					ArrayList<String> list = new ArrayList<String>();
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject apk = jsonArray.getJSONObject(i);
						String packageName = apk.getString("package");
						Boolean b = map.get(packageName);
						if (b != null) {
							// 判断是否gh_version是否相同
							String gh_version = (String) PackageUtils
									.getMetaData(context, packageName, "gh_version");
							if (gh_version != null) {
								gh_version = gh_version.substring(2);
								// 判断gh_version是否相同
								if (gh_version.equals(apk
										.getString("gh_version"))) {
									// 判断version是否相同
									String version = PackageUtils
											.getVersionByPackage(context,
													packageName);
									if (version.equals(apk.getString("version"))) {
										// 版本相同,无需显示插件更新,继续查看是否有可更新的游戏包
										continue;
									}
								}
							}
							list.add(packageName);
						}
					}
					if (RunningUtils.isEqualsTop(context,
							DownloadManagerActivity.class.getName())) {
						// 当前topActivity为DownloadManagerActivity
						EventBus.getDefault().post(new EBMiPush("mipush_plugin", list));
					} else {
						Intent intent2 = new Intent(context,
								DownloadManagerActivity.class);
						intent2.putExtra("currentItem", 1);
						intent2.putExtra("isPushIntent", true);
						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", "mipush_plugin");
					intent2.putExtra("data", jsonObject.toString());
					intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent2);
				}
				break;
			case 2:
				String tag = jsonObject.getString("tag");
				String[] tags = tag.split(",");
				JSONArray array = new JSONArray();
				for (int i = 0; i < tags.length; i++) {
					array.put(tags[i]);
				}
				jsonObject.put("tag", array);
				if (RunningUtils.isRunning(context)) {
					// 应用正在运行,前台或后台
					Gson gson = new Gson();
					GameEntity infoEntity = gson.fromJson(
							jsonObject.toString(), GameEntity.class);
					// if (isEquals(context, GameEntity.class.getName())) {
					// // 当前topActivity为GameEntity
					// EventBus.getDefault().post(
					// new EventBusMiPush("mipush_new_game",
					// infoEntity));
					// } else {
					AppController.put("GameEntity", infoEntity);
					Intent intent3 = new Intent(context,
							GameDetailActivity.class);
					intent3.putExtra("entrance", "小米推送");
					intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent3);
					// }
				} else {
					// 应用未在运行
					Intent intent3 = new Intent(context,
							SplashScreenActivity.class);
					intent3.setAction(Intent.ACTION_MAIN);
					intent3.addCategory(Intent.CATEGORY_LAUNCHER);
					Gson gson = new Gson();
					GameEntity infoEntity = gson.fromJson(
							jsonObject.toString(), GameEntity.class);
					intent3.putExtra("from", "mipush_new_game");
					AppController.put("GameEntity", infoEntity);
					intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent3);
				}
				break;
			default:
				break;
			}
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
	}

	private ArrayMap<String, Boolean> getInstalledMapFromLocal(Context context) {
		ArrayMap<String, Boolean> map = new ArrayMap<String, Boolean>();
		ArrayList<String> list = getAllPackageName(context);
		for (String str : list) {
			map.put(str, true);
		}
		return map;
	}

	private ArrayList<String> getAllPackageName(Context context) {
		ArrayList<String> list = new ArrayList<String>();
		List<PackageInfo> packageInfos = context.getPackageManager()
				.getInstalledPackages(0);
		for (int i = 0, size = packageInfos.size(); i < size; i++) {
			PackageInfo packageInfo = packageInfos.get(i);
			if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				list.add(packageInfo.packageName);
			}
		}
		return list;
	}
}
