
package com.zkjc.common.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

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

public class DBManager {

    private DBHelper helper;
    private SQLiteDatabase db;

    public DBManager(Context context) {
        helper = new DBHelper(context);
        db = helper.getWritableDatabase();
    }

    /**
     * Add some fingers mode to db.
     *
     * @param fingers
     */
    public void add(List<Finger> fingers) {
        db.beginTransaction();
        try {
            for (Finger finger : fingers) {
                db.execSQL("INSERT INTO " + DBHelper.TABLE_NAME + " VALUES(null, ?)", new Object[] {
                    finger.feature
                });
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    public long addFeature(Finger finger) {
        /*
         * db.beginTransaction(); try { db.execSQL("INSERT INTO " + DBHelper.TABLE_NAME +
         * " VALUES(null, ?)", new Object[]{ finger.feature }); db.setTransactionSuccessful(); }
         * finally { db.endTransaction(); }
         */
        ContentValues content = new ContentValues();
        content.put("feature", finger.feature);
        long row = db.insert(DBHelper.TABLE_NAME, null, content);
        return row;
    }

    public List<Finger> getAllData() {
        ArrayList<Finger> fingers = new ArrayList<Finger>();
        Cursor cursor = getAllDataCursor();
        while (cursor.moveToNext()) {
            Finger finger = new Finger();
            finger._id = cursor.getInt(cursor.getColumnIndex("_id"));
            finger.feature = cursor.getString(cursor.getColumnIndex("feature"));
            fingers.add(finger);
        }
        cursor.close();
        return fingers;
    }

    private Cursor getAllDataCursor() {
        Cursor cursor = db.rawQuery("SELECT * FROM " + DBHelper.TABLE_NAME, null);
        return cursor;
    }

    public void deleteAllData() {
        /*
         * int id; ArrayList<Integer> idList = new ArrayList<Integer>(); Cursor cursor =
         * getAllDataCursor(); while(cursor.moveToNext()) { id =
         * cursor.getInt(cursor.getColumnIndex("_id")); idList.add(id); } for(int i = 0; i <
         * idList.size(); i++) { String where = "_id = ?"; String[] whereValue ={
         * Integer.toString(idList.get(i)) }; db.delete(DBHelper.TABLE_NAME, where, whereValue); }
         */
        // db.delete(DBHelper.TABLE_NAME,null,null);
        String sql = "DROP TABLE IF EXISTS " + DBHelper.TABLE_NAME;
        db.execSQL(sql);
        helper.onCreate(db);
        db = helper.getWritableDatabase();
    }

    public void  deleteById(int id) {
        String sql = "DELETE * FROM " + DBHelper.TABLE_NAME + " WHERE _id="+ id;
        db.execSQL(sql);
    }

    public void closeDB() {
        db.close();
    }
}
