package com.android.chmo.db;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.x;

/**
 * 数据库基类
 */
public abstract class DBHelper {
    private DbManager db;

    public DBHelper() {
        DbManager.DaoConfig config = new DbManager.DaoConfig()
                .setDbName(getDbName())
                .setDbVersion(getDbVersion())
                .setAllowTransaction(true)
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        // 开启WAL, 对写入加速提升巨大
                        db.getDatabase().enableWriteAheadLogging();
                    }
                })
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        onDbUpgrade(db, oldVersion, newVersion);
                    }
                });
        db = x.getDb(config);
    }

    public DbManager getDbManager() {
        return db;
    }


    protected abstract String getDbName();

    protected abstract int getDbVersion();

    protected abstract void onDbUpgrade(DbManager db, int oldVersion, int newVersion);

    public void save(Object obj) {
        try {
            db.save(obj);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void saveOrUpdate(Object obj) {
        try {
            db.saveOrUpdate(obj);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void delete(Object obj) {
        try {
            db.delete(obj);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void delete(Class<?> obj, WhereBuilder where) {
        try {
            db.delete(obj, where);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


}
