package de.eightbitboy.hijacr.data.database;

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

import java.util.List;

import de.eightbitboy.hijacr.data.dao.Comic;
import de.eightbitboy.hijacr.data.dao.ComicDao;
import de.eightbitboy.hijacr.data.dao.DaoMaster;
import de.eightbitboy.hijacr.data.dao.DaoSession;

public class Database {
	public static String DB_NAME = "comics.dao.db";

	private static Database instance;

	private Context context;

	private SQLiteDatabase db;

	private DaoMaster master;

	private Database(Context context) {
		this.context = context;
		setUp();
		insertDefaultData();
	}

	public static synchronized Database getInstance(Context context) {
		if (instance == null) {
			instance = new Database(context);
		}

		return instance;
	}

	private void setUp() {
		db = new DaoMaster.DevOpenHelper(context, DB_NAME, null).getWritableDatabase();
		master = new DaoMaster(db);
	}

	private void insertDefaultData() {
		DaoSession session = master.newSession();
		ComicDao dao = session.getComicDao();

		Comic comic;

		if (dao.load(4L) == null) {
			comic = new Comic(
					4L,
					"extralife",
					"ExtraLife",
					"http://www.myextralife.com/",
					"http://www.myextralife.com/comic/06172001/",
					"",
					".comic",
					".prev_comic_link",
					".next_comic_link",
					false);
			dao.insert(comic);
		}
	}

	public List<Comic> getAllComics() {
		DaoSession session = master.newSession();
		ComicDao dao = session.getComicDao();

		return dao.loadAll();
	}

	public Comic getComicById(long id) {
		DaoSession session = master.newSession();
		ComicDao dao = session.getComicDao();
		return dao.load(id);
	}
}

@@ -935,89 +935,139 @@
 %7D%0A%0A%09
-private void insertDefaultData() %7B%0A%09%09DaoSession session = master.newSession();
+/**%0A%09 * Populate the empty database with comic data.%0A%09 */%0A%09private void insertDefaultData() %7B%0A%09%09if (getAllComics().isEmpty()) %7B
 %0A%09%09
+%09
 Comi
@@ -1081,32 +1081,29 @@
 o = 
-session.getComic
+createSession
 Dao();%0A
-%0A
+%09
 %09%09Co
@@ -1118,38 +1118,8 @@
 c;%0A%0A
-%09%09if (dao.load(4L) == null) %7B%0A
 %09%09%09c
@@ -1428,240 +1428,167 @@
 %7B%0A%09%09
-DaoSession session = master.newSession();%0A%09%09ComicDao dao = session.getComicDao();%0A%0A%09%09return dao.loadAll();%0A%09%7D%0A%0A%09public Comic getComicById(long id) %7B%0A%09%09DaoSession session = master.newSession();%0A%09%09ComicDao dao = session.getComic
+return createSessionDao().loadAll();%0A%09%7D%0A%0A%09public Comic getComicById(long id) %7B%0A%09%09return createSessionDao().load(id);%0A%09%7D%0A%0A%09private ComicDao createSession
 Dao()
-;
+ %7B
 %0A%09%09r
@@ -1597,19 +1597,40 @@
 urn 
-dao.load(id
+master.newSession().getComicDao(
 );%0A%09

Improve database code