package com.gh.gamecenter.manager;

import android.content.Context;

import com.gh.gamecenter.db.GameDao;
import com.gh.gamecenter.db.info.GameInfo;
import com.gh.gamecenter.entity.ApkEntity;

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

public class GameManager {

	private GameDao dao;

	public GameManager(Context context) {
		dao = new GameDao(context);
	}

	public void addOrUpdate(GameInfo entity) {
		if (dao.find(entity.getPackageName()) == null) {
			dao.add(entity);
		}
	}

	public void addOrUpdate(ArrayList<ApkEntity> apk, String gameId, String gameName) {
		if (apk == null || apk.isEmpty()) {
			return;
		}
		ArrayList<GameInfo> list = new ArrayList<>();
		ArrayList<String> packageNames = new ArrayList<>();
		for (ApkEntity apkEntity : apk) {
			packageNames.add(apkEntity.getPackageName());
		}
		if (packageNames.isEmpty()) {
			return;
		}
		List<GameInfo> result = dao.findAll(packageNames);
		for (GameInfo gameInfo : result) {
			packageNames.remove(gameInfo.getPackageName());
		}
		for (String packageName : packageNames) {
			list.add(new GameInfo(packageName, gameId, gameName));
		}
		if (list.size() != 0) {
			dao.addAll(list);
		}
	}

	public void addGame(GameInfo entity) {
		dao.add(entity);
	}

	public GameInfo findGame(String packageName) {
		return dao.find(packageName);
	}

	public void deleteGame(String packageName) {
		dao.delete(packageName);
	}

	public List<GameInfo> getAllGame() {
		return dao.getAll();
	}

	public void updateGame(GameInfo entity) {
		dao.update(entity);
	}

}
