<repo_name>segunAA/tbible<file_sep>/db.py
from sqlalchemy import create_engine
from datetime import datetime

class Bible():
	
	reader = create_engine("sqlite:///ampc.sqlite3")

	def __init__(self):
		pass

	def getBook(self, book):
		sql = '''	SELECT osis, human, chapters 
				FROM books 
				WHERE human = '{book}' OR osis='{book}' 
				LIMIT 1
		'''.format(book=book)

		return self.reader.execute(sql).fetchall()[0].osis if len(self.reader.execute(sql).fetchall()) > 0 else False
				

	def getPassage(self, book, verse):
		id = self.getVerseID(book, verse)
		sql = '''	SELECT * FROM verses LIMIT {id}, 10
		'''.format(id=(id-1))

		return self.reader.execute(sql).fetchall()

	def getVerseID(self, book, verse):
		sql = '''	SELECT id FROM verses WHERE book='{book}' AND verse='{verse}'
		'''.format(book=book, verse=verse)
		return self.reader.execute(sql).fetchone().id

	def finder(self, query):
		
		and_expanded = 'AND'.join([" unformatted LIKE '%{}%' ".format(a.strip()) for a in query.split() if len(a) > 3])
		or_expanded = 'OR'.join([" unformatted LIKE '%{}%' ".format(a.strip()) for a in query.split() if len(a) > 3])

		and_sql = "SELECT * FROM verses WHERE {query} ORDER BY id LIMIT 10".format(query=and_expanded)		
		or_sql = "SELECT * FROM verses WHERE {query} ORDER BY id LIMIT 10".format(query=or_expanded)		


		return dict(
					ando=self.reader.execute(and_sql).fetchall(), 
					oro=self.reader.execute(or_sql).fetchall()
		)



class App():

	connector = create_engine("sqlite:///tbible.db")

	def __init__(self):
		sql = '''	CREATE TABLE IF NOT EXISTS 
					cache (
						id INTEGER PRIMARY KEY, 
						created_at TEXT, 
						book TEXT, 
						verse TEXT, 
						success TEXT
		)
		'''
		
		self.connector.execute(sql)

		sql = '''	CREATE TABLE IF NOT EXISTS 
					bookmark (
						id INTEGER PRIMARY KEY, 
						created_at TEXT, 
						book TEXT, 
						verse TEXT
		)
		'''

		self.connector.execute(sql)

	def bookmark(self):
		sql = "SELECT book, verse FROM cache ORDER BY id DESC LIMIT 1"
		memory = self.connector.execute(sql).fetchone()

		#check if book mark exists
		sql = "SELECT id FROM bookmark WHERE book='{book}' AND verse='{verse}'".format(book=memory.book, verse=memory.verse)
		records = self.connector.execute(sql).fetchall()
		recs = len(records)

		if recs == 0:
			sql = "INSERT INTO bookmark (created_at, book, verse) VALUES ('{now}', '{book}', '{verse}')".format(now=datetime.now(), book=memory.book, verse=memory.verse)
			self.connector.execute(sql)

	def getBookmarked(self):
		sql = "SELECT * FROM bookmark ORDER BY id DESC LIMIT 20"
		verses = self.connector.execute(sql).fetchall()
		return verses

	def logger(self, book, verse):
		sql = '''	INSERT INTO cache (created_at, book, verse) 
					VALUES ('{now}', '{book}', '{verse}')
		'''.format(now=datetime.now(), book=book, verse=verse)
		self.connector.execute(sql)

<file_sep>/ui.py
from db import Bible, App


class UX():

	bible = Bible()
	cxn = App()

	def __init__(self):
		pass

	def welcome(self):
		print("Welcome to the Terminal Bible App!")
		print("==================================\n")


	def readVerses(self):
		book = input("Please select the book you want to read from: ")
		chapter = input("Please select the chapter you want to read from: ")
		verse = input("Please select the verse you want to start from: ")

		book = self.bible.getBook(book)
		verse = "{chapter}.{verse}".format(chapter=chapter, verse=str(verse).zfill(3))


		passage = self.bible.getPassage(book, verse)
		self.cxn.logger(book, verse)

		print("\n")
		for v in passage:
			print(v)

		print("\n")
	
	def bookmarkVerses(self):
		self.cxn.bookmark()

	def viewBookmarkedVerses(self):
		verses = self.cxn.getBookmarked()
		for verse in verses:
			print(verse)

	def search(self):
		query = input("Enter search keyword: ")
		result = self.bible.finder(query)

		for rec in result['ando']:
			print(rec)

		for rec in result['oro']:
			print(rec)

	def printHelp(self):
		apphelp = '''
			Available options:
			==================
			q - to quit
			b - to bookmark the last verse read
			v - to view bookmarked verses
			h - to repeat this message 
			s - to search the bible 
			r - to read verse
			'''
		print(apphelp)<file_sep>/app.py
from db import Bible, App
from ui import UX

ux = UX()
# bible = Bible()
# passage = bible.reader.execute("SELECT * FROM verses LIMIT 10")

cxn = App()

def app():
	# for verse in passage:
	# 	print(verse)
	ux.welcome()
	while True:

		action = input(": ")

		if action == "q": 
			break 
		elif action == 's':
			ux.search()			
		elif action == 'r':
			ux.readVerses()			
		elif action == 'v':
			ux.viewBookmarkedVerses()			
		elif action == 'b':
			ux.bookmarkVerses()			
		elif action == "h": 
			ux.printHelp()
		else:
			ux.printHelp()

if __name__ == "__main__":
	app()