package com.gh.gamecenter.db;

import android.content.Context;

import com.gh.gamecenter.db.info.GameInfo;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;

import java.sql.SQLException;
import java.util.List;

public class GameDao {
	
	private DatabaseHelper helper;
	private Dao<GameInfo, String> dao;

	public GameDao(Context context) {
		try {
			helper = DatabaseHelper.getHelper(context);
			dao = helper.getDao(GameInfo.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加一个游戏
	 */
	public void add(GameInfo entity) {
		try {
			dao.create(entity);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加多个个游戏
	 */
	public void addAll(List<GameInfo> list) {
		try {
			dao.create(list);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除一个游戏
	 */
	public void delete(String packageName) {
		try {
			dao.deleteById(packageName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据包名获取某一个游戏
	 */
	public GameInfo find(String packageName) {
		try {
			return dao.queryForId(packageName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据包名获取多个游戏
	 */
	public List<GameInfo> findAll(List<String> packageNames) {
		try {
			QueryBuilder<GameInfo, String> builder = dao.queryBuilder();
			Where where = builder.where();
			for (int i = 0, size = packageNames.size(); i < size; i++) {
				if (i == 0) {
					where.eq("packageName", packageNames.get(i));
				} else {
					where.or().eq("packageName", packageNames.get(i));
				}
			}
			return builder.query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取所有的游戏
	 */
	public List<GameInfo> getAll() {
		try {
			return dao.queryForAll();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 更新游戏
	 */
	public void update(GameInfo entity) {
		try {
			dao.update(entity);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
