package com.chaoran.db;

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

import java.util.*;

public class DBManager {
	private SqlHelpUtil helper;
	private SQLiteDatabase db;

	public DBManager(Context context) {
		helper = new SqlHelpUtil(context);
		// 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
		// mFactory);
		// 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
		db = helper.getWritableDatabase();
	}

	/*
	 * 判断表是否创建SELECT COUNT(*) as TabCount FROM sqlite_master where type='table'
	 * and name='T1'
	 */
	public int existsTable(String tableName) {
		String sql = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='"
				+ tableName + "' ";
		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		int count = cursor.getInt(0);
		cursor.close();
		return count;
	}

	public int rsCount(String tableName) {
		String sql = "SELECT COUNT(*)  FROM " + tableName + ";";
		Cursor cursor = db.rawQuery(sql, null);
		int count=0;
		if(cursor.moveToFirst()){
			count = cursor.getInt(0);			
		}
		cursor.close();
		return count;
	}
    public void batchSave(String sql,Map map){
    	Set<String> set = map.keySet();
    	db.beginTransaction();
		for (String s : set) {
			System.out.println(s+"--=============-"+map.get(s));
			db.execSQL(sql.toString(), new Object[]{s,map.get(s)});
		}
		db.setTransactionSuccessful();
		db.endTransaction();
    }
	public void batchSave(List<HashMap> list, String tableName) {
		HashMap map = (HashMap) list.get(0);
		Set<String> set = map.keySet();
		ArrayList<String> keys = new ArrayList<String>();
		StringBuilder sql = new StringBuilder("insert into  ");
		sql.append(tableName).append("(");
		StringBuilder column = new StringBuilder();
		StringBuilder value = new StringBuilder();
		for (String key : set) {
			if(key.toUpperCase().equals("ROWNUMBER")){
				continue;
			}
			keys.add(key);
			if (column.length() > 0) {
				column.append(",");
				value.append(",");
			}
			column.append(key);
			value.append("?");
		}
		sql.append(column.toString()).append(") values (").append(value)
				.append(")");
		int len = keys.size();
		System.out.println(sql.toString());
		String runSql=sql.toString();
		try {
			db.beginTransaction();
			int listLen = list.size();
			Object param[] = new Object[len];
			for (HashMap hmp : list) {
				for (int i = 0; i < len; i++) {
					Object tempObject=hmp.get(keys.get(i));
//					System.out.println(keys.get(i)+"---"+tempObject);
//					if(tempObject instanceof byte[]){
//						System.out.println("length---"+((byte[])tempObject).length);
//						ByteArrayInputStream bin = new ByteArrayInputStream((byte[])tempObject);
//						try {
//							ObjectInputStream oin = new ObjectInputStream(bin);
//							DanJuEntity danJuEntity=(DanJuEntity) oin.readObject();
//							System.out.println(danJuEntity.pageNr + "--------");
//						} catch (Exception e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
//					}
					if(tempObject==null){
						param[i]="";
					}else{
					    param[i] = tempObject;
					}
				}
				db.execSQL(runSql, param);
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	public void exeSql(String sql) {
		db.execSQL(sql);
	}

	public void exeSql(String sql, Object object[]) {
		db.execSQL(sql, object);
	}

	public Cursor query(String sql) {
		System.out.println(sql);
		return db.rawQuery(sql, null);

	}

	/**
	 * add persons
	 * 
	 * @param persons
	 */
	// public void add(List<Person> persons) {
	// db.beginTransaction(); //开始事务
	// try {
	// for (Person person : persons) {
	// db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new
	// Object[]{person.name, person.age, person.info});
	// }
	// db.setTransactionSuccessful(); //设置事务成功完成
	// } finally {
	// db.endTransaction(); //结束事务
	// }
	// }
	//
	// /**
	// * update person's age
	// * @param person
	// */
	// public void updateAge(Person person) {
	// ContentValues cv = new ContentValues();
	// cv.put("age", person.age);
	// db.update("person", cv, "name = ?", new String[]{person.name});
	// }
	//
	// /**
	// * delete old person
	// * @param person
	// */
	// public void deleteOldPerson(Person person) {
	// db.delete("person", "age >= ?", new
	// String[]{String.valueOf(person.age)});
	// }
	//
	// /**
	// * query all persons, return list
	// * @return List<Person>
	// */
	// public List<Person> query() {
	// ArrayList<Person> persons = new ArrayList<Person>();
	// Cursor c = queryTheCursor();
	// while (c.moveToNext()) {
	// Person person = new Person();
	// person._id = c.getInt(c.getColumnIndex("_id"));
	// person.name = c.getString(c.getColumnIndex("name"));
	// person.age = c.getInt(c.getColumnIndex("age"));
	// person.info = c.getString(c.getColumnIndex("info"));
	// persons.add(person);
	// }
	// c.close();
	// return persons;
	// }
	//
	// /**
	// * query all persons, return cursor
	// * @return Cursor
	// */
	// public Cursor queryTheCursor() {
	// Cursor c = db.rawQuery("SELECT * FROM person", null);
	// return c;
	// }

	/**
	 * close database
	 */
	public void closeDB() {
		db.close();
		helper.close();
		db = null;
		helper = null;
	}
}