package com.gh.gamecenter.manager;

import android.content.Context;
import android.support.v4.util.ArrayMap;

import com.gh.common.util.PackageUtils;
import com.gh.common.util.TrafficUtils;
import com.gh.gamecenter.db.ConcernDao;
import com.gh.gamecenter.db.info.ConcernInfo;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBConcernChanged;

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

import de.greenrobot.event.EventBus;

public class ConcernManager {

	private Context context;
	private ConcernDao dao;

	public ConcernManager(Context context) {
		this.context = context;
		dao = new ConcernDao(context);
	}

	/**
	 * 根据id判断是否已关注
	 */
	public boolean isConcern(String id) {
		ConcernInfo concernEntity = dao.find(id);
		return concernEntity != null && concernEntity.isConcern();
	}

	/**
	 * 根据GameEntity添加一个关注
	 */
	public void addByEntity(final GameEntity entity) {
		new Thread() {
			@Override
			public void run() {
				ConcernInfo concernEntity = findConcernById(entity.getId());
				if (concernEntity == null) {
					concernEntity = new ConcernInfo();
					concernEntity.setId(entity.getId());
					concernEntity.setTime(System.currentTimeMillis());
					concernEntity.setIcon(entity.getIcon());
					concernEntity.setGameName(entity.getName());
					concernEntity.setConcern(true);
					String tag = "已关注";
					HashMap<String, Boolean> packageNames = new HashMap<>();
					int weight = 1;
					int quantity = 0;
					for (ApkEntity apkEntity : entity.getApk()) {
						if (PackageManager.isInstalled(apkEntity.getPackageName())) {
							quantity++;
							packageNames.put(apkEntity.getPackageName(), true);
						} else {
							packageNames.put(apkEntity.getPackageName(), false);
						}
					}
					if (quantity > 0) {
						weight++;
						tag = "已关注,已安装";
					}
					concernEntity.setInstalledQuantity(quantity);
					concernEntity.setInstalled(weight != 1);
					concernEntity.setTag(tag);
					concernEntity.setPackageNames(packageNames);
					long traffic = TrafficUtils
							.getInstance(context)
							.getTraffic(new ArrayList<>(packageNames.keySet()));
					concernEntity.setTraffic(traffic);
					if (traffic > 0) {
						weight++;
					}
					concernEntity.setWeight(weight);
					addConcern(concernEntity);
				} else {
					concernEntity.setTime(System.currentTimeMillis());
					concernEntity.setIcon(entity.getIcon());
					concernEntity.setConcern(true);
					HashMap<String, Boolean> packageNames = new HashMap<>();
					int quantity = 0;
					for (ApkEntity apkEntity : entity.getApk()) {
						if (PackageManager.isInstalled(apkEntity.getPackageName())) {
							quantity++;
							packageNames.put(apkEntity.getPackageName(), true);
						} else {
							packageNames.put(apkEntity.getPackageName(), false);
						}
					}
					concernEntity.setInstalledQuantity(quantity);
					concernEntity.setTag("已关注,已安装");
					concernEntity.setPackageNames(packageNames);
					long traffic = TrafficUtils
							.getInstance(context)
							.getTraffic(new ArrayList<>(packageNames.keySet()));
					concernEntity.setTraffic(traffic);
					int weight = 2;
					if (traffic > 0) {
						weight++;
					}
					concernEntity.setWeight(weight);
					updateByConcern(concernEntity);
				}
				EventBus.getDefault().post(new EBConcernChanged(entity.getId(), true));
			}
		}.start();
	}

	/**
	 * 根据GameEntity更新关注
	 */
	public void updateByEntity(com.gh.gamecenter.db.info.GameInfo gameEntity) {
		String packageName = gameEntity.getPackageName();
		ConcernInfo concernEntity = findConcernById(gameEntity.getId());
		if (concernEntity != null) {
			concernEntity.setTime(System.currentTimeMillis());
			if ((concernEntity.isConcern() && concernEntity.isInstalled())
					|| (!concernEntity.isConcern() && concernEntity
							.isInstalled())) {
				concernEntity.getPackageNames().put(packageName, true);
				concernEntity.setInstalledQuantity(concernEntity
						.getInstalledQuantity() + 1);
				updateByConcern(concernEntity);
			} else if (concernEntity.isConcern()
					&& !concernEntity.isInstalled()) {
				concernEntity.setTag("已关注,已安装");
				concernEntity.setInstalled(true);
				concernEntity.setInstalledQuantity(1);
				concernEntity.getPackageNames().put(packageName, true);
				int weight = concernEntity.getWeight() + 1;
				concernEntity.setWeight(weight);
				updateByConcern(concernEntity);
			}
		} else {
			concernEntity = new ConcernInfo();
			concernEntity.setId(gameEntity.getId());
			concernEntity.setTime(System.currentTimeMillis());
			HashMap<String, Boolean> packageNames = new HashMap<>();
			packageNames.put(packageName, true);
			concernEntity.setPackageNames(packageNames);
			concernEntity.setInstalled(true);
			concernEntity.setConcern(false);
			concernEntity.setTag("已安装");
			concernEntity.setWeight(1);
			concernEntity.setInstalledQuantity(1);
			if (gameEntity.getGameName() != null) {
				concernEntity.setGameName(gameEntity.getGameName());
			} else {
				concernEntity.setGameName(PackageUtils.getNameByPackageName(
						context, packageName));
			}
			addConcern(concernEntity);
		}
	}

	/**
	 * 获取已安装游戏的集合
	 */
	public List<ConcernInfo> getInstalledGame() {
		return dao.getInstalled();
	}

	/**
	 * 获取已关注游戏的集合
	 */
	public List<ConcernInfo> getConcernGame() {
		return dao.getConcern(0);
	}

	public List<ConcernInfo> getConcernGame(int number) {
		return dao.getConcern(number);
	}

	/**
	 * 根据包名 更新关注
	 */
	public void updateByPackageName(String packageName) {
		for (ConcernInfo concernEntity : getAllConcern()) {
			Boolean isInstalled = concernEntity.getPackageNames().get(
					packageName);
			if (isInstalled != null && isInstalled) {
				if (concernEntity.getInstalledQuantity() - 1 == 0) {
					if (!concernEntity.isConcern()
							&& concernEntity.isInstalled()) {
						deleteConcern(concernEntity.getId());
					} else {
						concernEntity.setTime(System.currentTimeMillis());
						concernEntity.setTag("已关注");
						concernEntity.setInstalled(false);
						concernEntity.setInstalledQuantity(0);
						concernEntity.getPackageNames().put(packageName, false);
						concernEntity.setWeight(concernEntity.getWeight() - 1);
						updateByConcern(concernEntity);
					}
				} else if (concernEntity.getInstalledQuantity() - 1 > 0) {
					concernEntity.setTime(System.currentTimeMillis());
					concernEntity.setInstalledQuantity(concernEntity
							.getInstalledQuantity() - 1);
					concernEntity.getPackageNames().put(packageName, false);
					updateByConcern(concernEntity);
				}
				break;
			}
		}
	}

	/**
	 * 获取所有的关注 按照权重和流量排序
	 */
	public List<ConcernInfo> getAllConcernBySort() {
		return getConcern(0);
	}

	/**
	 * 获取权重和流量排序靠前的关注
	 * 
	 * @param number
	 *            数量
	 * @return list
	 */
	public List<ConcernInfo> getConcern(int number) {
		return dao.get(number);
	}

	/**
	 * 添加一个关注
	 */
	public void addConcern(ConcernInfo entity) {
		dao.add(entity);
	}

	/**
	 * 删除一个关注
	 */
	public void deleteConcern(String id) {
		ConcernInfo concernEntity = findConcernById(id);
		if (concernEntity.isConcern() && concernEntity.isInstalled()) {
			concernEntity.setTime(System.currentTimeMillis());
			concernEntity.setConcern(false);
			concernEntity.setWeight(concernEntity.getWeight() - 1);
			concernEntity.setTag("已安装");
			updateByConcern(concernEntity);
		} else {
			dao.delete(id);
		}
		EventBus.getDefault().post(new EBConcernChanged(id, false));
	}

	/**
	 * 获取某一个关注
	 */
	public ConcernInfo findConcernById(String id) {
		return dao.find(id);
	}

	/**
	 * 获取关注列表
	 */
	public List<ConcernInfo> getAllConcern() {
		return dao.getAll();
	}

	/**
	 * 获取关注map
	 */
	public ArrayMap<String, ConcernInfo> getConcernMap() {
		ArrayMap<String, ConcernInfo> map = new ArrayMap<>();
		for (ConcernInfo entity : dao.getAll()) {
			map.put(entity.getId(), entity);
		}
		return map;
	}

	/**
	 * 更新关注列表
	 */
	public void updateByConcern(ConcernInfo entity) {
		dao.update(entity);
	}
}
