package com.gh.download;

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

import com.gh.common.util.Utils;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DBHelper extends OrmLiteSqliteOpenHelper {

    private static final String DB_NAME = "gh_download.db";  
    private static final int VERSION = 3;
    
    /**
	 * downloadDao ，每张表对应一个
	 */
	private Dao<DownloadEntity, String> downloadDao;
  
    private DBHelper(Context context) {
        super(context, DB_NAME, null, VERSION);  
    }  
  
    @Override  
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    	try {
    		Utils.log("ormlite_test", "onCreate ====================");
			TableUtils.createTable(connectionSource, DownloadEntity.class);
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}   
    }  
  
    @Override  
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource,
                          int oldVersion,
                          int newVersion) {
    	try {
			TableUtils.dropTable(connectionSource, DownloadEntity.class, true);
            onCreate(database, connectionSource);
    	} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
    }  
  
    private static DBHelper mInstance;  
  
    /** 
     * 单例获取该Helper 
     *  
     * @param context 
     * @return 
     */  
    public static synchronized DBHelper getInstance(Context context) {
        context = context.getApplicationContext();  
        if (mInstance == null) {
            synchronized (DBHelper.class) {
                if (mInstance == null) {
                    mInstance = new DBHelper(context);
                }
            }
        }
        return mInstance;  
    }  
  
    public Dao<DownloadEntity, String> getDownloadDao() {
    	try {
			if (downloadDao == null) {
				downloadDao = getDao(DownloadEntity.class);
			}
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
    	return downloadDao;
    } 
  
    /** 
     * 释放资源 
     */  
    @Override  
    public void close() {
        super.close();  
        downloadDao= null;
    }

}  