package jp.agentec.abook.abv.bl.common.db.impl;

import jp.agentec.abook.abv.bl.common.exception.ABVRuntimeException;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.ABVDataOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class StandardSQLiteOpenHelper extends SQLiteOpenHelper implements jp.agentec.abook.abv.bl.common.db.SQLiteOpenHelper {
	private static final String TAG = "StandardSQLiteOpenHelper";
	public static ABVDataOpenHelper abhelper;
	private Context context;

	public StandardSQLiteOpenHelper(Context context, String name, int version) {
		super(context, name, null, version);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		abhelper.onCreate(new StandardSQLiteDatabase(db));
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		abhelper.onUpgrade(new StandardSQLiteDatabase(db), oldVersion, newVersion);
	}

	public boolean isCreated() {
		return abhelper.isCreated();
	}

	public Throwable getLastError() {
		return abhelper.getLastError();
	}

	@Override
    public StandardSQLiteDatabase openDatabase() {
		if (context == null) {
			throw new ABVRuntimeException("Android context is null. You must call init()");
		}
		
		abhelper = new ABVDataOpenHelper();

		Logger.i(TAG, "open standard database start.");
		StandardSQLiteDatabase db = new StandardSQLiteDatabase(getWritableDatabase()); // このタイミングでDBが生成され、onCreateが呼び出される
		Logger.i(TAG, "open standard database completed.");

		if (!isCreated()) {
			throw new ABVRuntimeException("Can't open or create database.", getLastError());
		}
		
		return db;
	}


}
