package com.gh.gamecenter.db;

import android.content.Context;

import com.gh.gamecenter.db.info.PackageInfo;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.lightgame.utils.Utils;

import java.util.List;

public class FilterDao {

    private DatabaseHelper helper;
    private Dao<PackageInfo, String> dao;

    public FilterDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            dao = helper.getDao(PackageInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public long getSince() {
        try {
            QueryBuilder<PackageInfo, String> builder = dao.queryBuilder();
            builder.orderBy("time", false).limit(1L);
            List<PackageInfo> list = builder.query();
            if (list != null && list.size() != 0) {
                return list.get(0).getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public boolean isFilter(String packageName) {
        try {
            PackageInfo filterEntity = dao.queryForId(packageName);
            if (filterEntity != null) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 添加一个过滤包名
     */
    public void add(PackageInfo entity) {
        try {
            dao.create(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加一堆过滤包名
     * MARK:必须保证list中packageName的唯一性
     */
    public void addAll(List<PackageInfo> list) {
        try {
            dao.create(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteAll(List<PackageInfo> list) {
        try {
            dao.delete(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一个过滤包名
     */
    public void delete(String packageName) {
        try {
            dao.deleteById(packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的过滤包名
     */
    public List<PackageInfo> getAll() {
        try {
            return dao.queryForAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取表中数据总数
     */
    public long getCount() {
        try {
            return dao.countOf();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}