package com.yuji.ec.db;

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

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

import com.yuji.ec.utility.Debug;

public class DatabaseHelper extends SQLiteOpenHelper {
	private static DatabaseHelper instance = null;
	private static List<IDao<?>> daoList = null;

	public static DatabaseHelper getInstance() {
		return instance;
	}

	public static void init(Context context) {
		if (instance != null) {
			return;
		}
		daoList = new ArrayList<IDao<?>>();
		daoList.add(NoteDao.getInstance());

		DatabaseHelper helper = new DatabaseHelper(context);
		SQLiteDatabase db = helper.getWritableDatabase();

		for (IDao<?> dao : daoList) {
			dao.init(db);
		}
	}

	public DatabaseHelper(Context context) {
		super(context, "EverClip.db", null, 1);
		instance = this;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			for (IDao<?> dao : daoList) {
				dao.onCreate(db);
				dao.init(db);
			}

			db.beginTransaction();
			try {
				for (IDao<?> dao : daoList) {
					dao.start(db);
				}
				db.setTransactionSuccessful();
			} finally {
				db.endTransaction();
			}
		} catch (Exception e) {
			Debug.d(this, null, e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

	}

}
