Editorial Workflows

Bible 2

public workflow

Install Workflow...

This workflow contains at least one Python script. Only use it if you trust the person who shared this with you, and if you know exactly what it does.

I understand, install the workflow!

This is a workflow for Editorial, a Markdown and plain text editor for iOS. To download it, you need to view this page on a device that has the app installed.

Description: A bible app
Thanks dgelessus!

Updated for editorial 1.3 (code for 1.2 is comemented) It's the selected chapter line.

Converted from my pythonista version.
This is not complete yet but it willl be.

You will need the database file in the GitHub from here:
https://github.com/TutorialDoctor/The-Bible-App

Use my Github Get workflow to download the github repo and move the bible.db file to the Documents folder.

Now with Light and Dark themes!

Shared by: Tutorial Doctor

Comments: Comment Feed (RSS)

There are no comments yet.

+ Add Comment

Workflow Preview
Select from List ?
Title
Color
List (Lines)
light dark
Multiple Selection
OFF
Show in Popover
OFF
Style ?
Variable Name
style
Value
Input
If… ?
Run the block if
style
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
light
Bible Light ?
Source Code
import ui,sqlite3,datetime,sound,console,clipboard,dialogs,re,editor,os,webbrowser,speech,fileinput,zipfile,webbrowser,json,editor

#--- VARIABLES
pairs={1: 'Genesis', 2: 'Exodus', 3: 'Leviticus', 4: 'Numbers', 5: 'Deuteronomy', 6: 'Joshua', 7: 'Judges', 8: 'Ruth', 9: '1 Samuel', 10: '2 Samuel', 11: '1 Kings', 12: '2 Kings', 13: '1 Chronicles', 14: '2 Chronicles', 15: 'Ezra', 16: 'Nehemiah', 17: 'Esther', 18: 'Job', 
19: 'Psalms', 20: 'Proverbs', 21: 'Ecclesiastes', 22: 'Song of Solomon', 23: 'Isaiah', 24: 'Jeremiah', 25: 'Lamentations', 26: 'Ezekiel', 27: 'Daniel', 28: 'Hosea', 29: 'Joel', 30: 'Amos', 31: 'Obadiah', 32: 'Jonah', 33: 'Micah', 34: 'Nahum', 35: 'Habakkuk', 36: 'Zephaniah', 37: 'Haggai', 38: 'Zechariah', 39: 'Malachi', 40: 'Matthew', 41: 'Mark', 42: 'Luke', 43: 'John', 44: 'Acts', 45: 'Romans', 46: '1 Corinthians', 47: '2 Corinthians', 48: 'Galatians', 49: 'Ephesians', 50: 'Philippians', 51: 'Colossians', 52: '1 Thessalonians', 53: '2 Thessalonians', 54: '1 Timothy', 55: '2 Timothy', 56: 'Titus', 57: 'Philemon', 58: 'Hebrews', 59: 'James', 60: '1 Peter', 61: '2 Peter', 62: '1 John', 63: '2 John', 64: '3 John', 65: 'Jude', 66: 'Revelation'}

local = os.path.join(os.path.expanduser("~"), "Documents")
database = local+'/bible-sqlite.db'
# I'd like to add a timestamp to notes, so:
time_stamp = datetime.datetime.today().strftime('%m_%d_%Y_%H:%M:%S')
# File name for our notes file (here for easy access)
save_file = 'favorites.txt'
thoughts_file='thoughts.txt'
bookmarks_file='bookmarks.txt'
translation='t_kjv'
backup='backup.txt'
fullscreen_preview=None


# We will load the following list into a list dialog
translations={"t_asv":"American Standard - ASV1901 (ASV)",
"t_bbe":"Bible in Basic English - (BBE)",
"t_dby":"Darby - (DBY)",
"t_kjv":"King James Version (KJV)",
"t_wbt":"Webster's Bible (WBT)",
"t_web":"World English Bible (WEB)",
"t_ylt":"Young's Literal Translation (YLT)"}
# END VARIABLES

images = {
	'0':'iob:share_32',
	'1':'iob:ios7_information_32',
	'2':'iob:ios7_videocam_32',
	'3':'iob:ios7_albums_outline_32',
	'4':'iob:camera_32',
	'5':'iob:calendar_24',
	'6':'iob:chatbox_working_24',
	'7':'iob:checkmark_circled_24',
	'8':'iob:clock_24',
	}

def create_assembly_folders():
	try:
		for folder in churches:
			document_directory=os.mkdir(folder)
	except:None


# Try to make a directory named 'Notes.' Do nothing if there is an exception error.
try:
	document_directory = os.mkdir(local+'/Notes')
except: None

"""
table_name: t_kjv
	records:
		b - book (int)
		c - chapter (int)
		v - verse (int)
		t - text (str)

table_name: key_english
	records:
		b - book (int)
		n - name (str)

table_name: bible_version_key
		id
		table
		abbreviation
	
American Standard - ASV1901 (ASV)
Bible in Basic English - (BBE)
Darby
King James Version (KJV)
Webster's Bible (WBT)
World English Bible (WEB)
Young's Literal Translation (YLT)
"""


#--- CLASSES			
# I will leave the results as a list so that I can load them into a tableview data source
# Textfield

# currently this class only backs up the thoughts text. hopefull it will bak up entire state of the app 


class MyTextFieldDelegate (object):
	def textfield_should_begin_editing(self, textfield):
		return True
	def textfield_did_begin_editing(self, textfield):
		pass
	def textfield_did_end_editing(self, textfield):
		if textfield.text != '':
			def show():
				search.hidden=False
				search.alpha=1
			ui.animate(show,.4)
			try:
				con = sqlite3.connect(database)
				cur = con.cursor()			
				substring= textfield.text
				sub_query="select b,c,v,t from {} where t like '%{}%'".format(translation,substring)
				sub_all=[x for x in cur.execute(sub_query)]
				table.data_source = ui.ListDataSource(sub_all)
				table.reload()
				matches.text=str(len(sub_all))
				#table.reload_data()
			except:
				None
	def textfield_should_return(self, textfield):
		textfield.end_editing()
		return True
	def textfield_should_change(self, textfield, range, replacement):
		return True
	def textfield_did_change(self, textfield):
		pass

#Textview
class MyTextViewDelegate (object):
	def textview_should_begin_editing(self, textview):
		return True
	def textview_did_begin_editing(self, textview):
		pass
	def textview_did_end_editing(self, textview):
		pass
	def textview_should_change(self, textview, range, replacement):
		return True
	def textview_did_change(self, textview):
		return True
	def textview_did_change_selection(self, textview):
		pass

#Tableview
class MyTableViewDelegate (object):
	def tableview_did_select(self, tableview, section, row):
		# Called when a row was selected.
		item = tableview.data_source.items[row]
		# Search results formatting
		search_selection.text =  '**'+str(pairs[item[0]])+' '+str(item[1])+': '+str(item[2])+'**'+'\n\n'+str(item[3])

	def tableview_did_deselect(self, tableview, section, row):
		# Called when a row was de-selected (in multiple selection mode).
		pass

	def tableview_title_for_delete_button(self, tableview, section, row):
		# Return the title for the 'swipe-to-***' button.
		return 'Delete'


# CLASSES
class MyTableViewDelegate2 (object):
	def tableview_did_select(self, tableview, section, row):
		# Called when a row was selected.
		cell = tableview.data_source.items[row]
		set_view_text(str(cell))
		header_label.text = tableview.data_source.items[row].strip('.txt').capitalize()
		#sound.play_effect('ui:click2')

	def tableview_did_deselect(self, tableview, section, row):
		# Called when a row was de-selected (in multiple selection mode).
		pass

	def tableview_title_for_delete_button(self, tableview, section, row):
		# Return the title for the 'swipe-to-***' button.
		return 'Trash it'
# END CLASSES

#--- FUNCTIONS
# closes the superview of the sender
def close(sender):
	sender.superview.superview.close()
	speech.stop()


# save text in a view to the clipboard
def clip(sender):
	clipboard.set(thought_bubble.text)
	console.alert('Saved to Clipboard')


# open a list dialog
def translate(sender):
	global translation
	show=dialogs.list_dialog('Translations',[trans for trans in translations])
	translation=show
	try:
		translation_label.text = translations[translation]
	except: None

	
# open the IOS share sheet
def share(sender):
	dialogs.share_text(thought_bubble.text)


# load sqlite3 query into a tableview as a result of a segmented control action
def test(sender):
	con = sqlite3.connect(database)
	cursor=con.cursor()
	# A query to get all old testament book names in the 'key_english' table 
	ot_query = 'select n from key_english where b < 40'
	ot_bks = [x[0] for x in cursor.execute(ot_query)]
	
	# A query to get all new testament book names in the 'key_english' table 
	nt_query = 'select n from key_english where b >= 40'
	nt_bks = [x[0] for x in cursor.execute(nt_query)]
	
	selected_testament = sender.segments[sender.selected_index]
	
	if selected_testament=='Old':
		books.data_source.items=ot_bks
	
	elif selected_testament=='New':
		books.data_source.items= nt_bks


# Updates the table and text views
def updates(*args):
	# Connect to the sqlite database and create a cursor to query it with
	con = sqlite3.connect(database)
	cursor=con.cursor()
	# Three argument parameters (all tanleviews) that were passed in using a lambda function.
	tbl_books = args[0]
	tbl_chapters = args[1]
	control_testaments = args[2]
	
	# A query to get all book names in the 'key_english' table
	all_bks_query = 'select n from key_english'
	all_bks = [x[0] for x in cursor.execute(all_bks_query)]
	
	# Store tableview selections
	selected_book = tbl_books.items[tbl_books.selected_row]
	#selected_chap = tbl_chapters.items[tbl_chapters.selected_row]['title'] editorial #v 1.2
	selected_chap = tbl_chapters.items[tbl_chapters.selected_row] #editorial v 1.3
	#selected_testament = control_testaments.segments[control_testaments.selected_index]
	
	
	# Select book from the key_english table where the name = the selected book/cell of a tableview
	num_query = "select b from key_english where n='{}'".format(selected_book)
	bk_num=[x for x in cursor.execute(num_query)][0][0]
	
	c = selected_chap # unnecessary perhaps but using 'c' is shorter.
	
	# Select chapter,verse,text from the t_kjv table where book = book number (tableview) and chapter = selected chapter
	txt_query = "select c,v,t from '{}' where b = '{}' AND c = '{}'".format(translation,bk_num,c)
	txt = [row for row in cursor.execute(txt_query)]
	# Format the text as -- ''+chapter+text -- ('' can be replaced with whatever prefix you want)
	txt_formatted = "\n".join("{} {}: {}\n".format('',c,t) for b,c,t in txt)
	
	# If the formatted text is an empty string, set the contents textview to a string
	# This is a quick fix if a user selects a chapter in a book that doesn't exist for that book
	if txt_formatted=='':
		contents.text = 'Chapter does not exist'
	
	# Otherwise, set the contents textview to the formatted text
	else:
		contents.text = txt_formatted
	# Set the heading label to the selected book plus the selected chapter (as a string)
	heading.text=selected_book+' '+str(selected_chap)


#	Save text/selected text in a textview to a file
def save_selection(sender):
	'''saves text/selected text in a textview to a file. If no text is selected, the entire text is saved.'''
	# Get the beginning of the textview selection
	beg= contents.selected_range[0]
	# Get the end of the textview selection
	end = contents.selected_range[1]
	# Get the entire text in the textview
	txt = contents.text
	# If text is selected (if there is a substring from beginning to end)...
	with open(local+'/Notes/'+save_file,'a') as outfile:
		if txt[beg:end] != '':
			# write the text to a file with a timestamp, the heading lable text, and the selected text.
			outfile.write('\n'+time_stamp+'\n'+heading.text+'\n\n'+txt[beg:end]+'\n')
		# Otherwise...
		else:
			# write the entire text to the file.
			outfile.write('\n'+time_stamp+'\n'+heading.text+'\n\n'+txt+'\n')
	# Play a sound
	#sound.play_effect('digital:ThreeTone2')
	# Alert the user that fhe file has been saved to the file.
	console.alert('Saved to {}'.format(save_file))

# Same logic as save_selection
def selectionToClipboard(sender):
	beg= contents.selected_range[0]
	end = contents.selected_range[1]
	txt = contents.text
	if txt[beg:end] != '':
		clipboard.set(clipboard.get()+'\n'+"**"+heading.text+"**"+'\n\n'+txt[beg:end]+'\n\n')
	else:
		clipboard.set(clipboard.get()+'\n'+"**"+heading.text+"**"+'\n\n'+txt+'\n\n')
	console.hud_alert('appended',duration=.1)
		

def selectionToThoughts(sender):
	console.hud_alert('captured',duration=.1)
	#sound.play_effect('rpg:Creak3')
	beg= contents.selected_range[0]
	end = contents.selected_range[1]
	txt = contents.text
	if txt[beg:end] != '':
		editor.insert_text("## "+heading.text+'\n\n'+txt[beg:end]+'\n\n')
		#editor.insert_text("**"+heading.text+"**"+'\n\n'+txt[beg:end]+'\n\n')
	else:
		editor.insert_text("## "+heading.text+'\n\n'+txt+'\n\n')
		#editor.insert_text("**"+heading.text+"**"+'\n\n'+txt+'\n\n')


# Shows the search window
def show_search(sender):
	def show():
		search.hidden=False
		search.alpha=1
	ui.animate(show,.4)

		
# Hides the search window
def hide_search(sender):
	def hide():
		search.alpha=0
	ui.animate(hide,.4)
	#search.present('sheet')
	#search.hidden=True

	
def clear_search(sender):
	search_field.text=''


def forward_to_thoughts(sender):
	editor.insert_text('\n\n'+search_selection.text+'\n')
	#editor.insert_text('\n\n'+'## '+search_selection.text+'\n')
	#sound.play_effect('rpg:BookFlip2')


# File name for our thoughts file.
def choose_file():
	global thoughts_file
	file_select= dialogs.list_dialog('Select A File',['New']+os.listdir(local+'/Notes'))
	if file_select=='New':
		thoughts_file = dialogs.input_alert('Name your thoughts file')+'.txt'
	elif file_select==None:
		pass
	else:
		thoughts_file= file_select


def view_files(sender):
	global thoughts_file
	file_select= dialogs.list_dialog('Select A File',['New']+os.listdir(local+'/Notes'))
	if file_select=='New':
		thoughts_file = dialogs.input_alert('Name your thoughts file')+'.txt'
	elif file_select==None:
		pass
	else:
		thoughts_file= file_select
	thoughts_title.text = thoughts_file


def add_mark(sender):
	# Store tableview selections
	# Connect to the sqlite database and create a cursor to query it with
	con = sqlite3.connect(database)
	cursor=con.cursor()
	selected_book = books.data_source.items[books.data_source.selected_row]
	#selected_chap = chapters.data_source.items[chapters.data_source.selected_row]['title']
	selected_chap = chapters.data_source.items[chapters.data_source.selected_row][0]
	#selected_testament = control_testaments.segments[control_testaments.selected_index]	
	# Select book from the key_english table where the name = the selected book/cell of a tableview
	num_query = "select b from key_english where n='{}'".format(selected_book)
	bk_num=[x for x in cursor.execute(num_query)][0][0]
	txt_query = "select c,v,t from '{}' where b = '{}' AND c = '{}'".format(translation,bk_num,selected_chap)
	txt = [row for row in cursor.execute(txt_query)]
	# Format the text as -- ''+chapter+text -- ('' can be replaced with whatever prefix you want)
	txt_formatted = "\n".join("{} {}: {}\n".format('',c,t) for b,c,t in txt)
	try:
		if selected_chap:
			book_marks.segments = book_marks.segments+tuple([selected_book+' '+str(selected_chap)+'\n'+txt_formatted])
	except: None


def load_mark(sender):
	txt=sender.segments[sender.selected_index]
	if txt=='':
		contents.text='empty'
	else:
		contents.text=txt
	heading.text = 'Bookmark'
	#heading.text=selected_book+' '+str(selected_chap)


def save_bookmarks(sender):
	bookmarks_file='bookmark: '+'test'+'.txt'
	txt=book_marks.segments
	for x in txt:
		with open(local+'/Notes/'+bookmarks_file,'a',encoding='utf-8')	as outfile:
			outfile.write(time_stamp+'\n'+str(x)+'\n')
	#sound.play_effect('rpg:BookFlip2')
	console.alert('Saved to {}'.format(bookmarks_file))


def clear_bookmarks(sendr):
	book_marks.segments=['']


def search_to_file(sender):
	tbl=table
	all = tbl.data_source.items
	string = ''.join('**'+pairs[x[0]]+' '+str(x[1])+': '+str(x[2])+'**\n\n'+str(x[3])+'\n\n' for x in all)
	with open(local+'/Notes/'+'search: '+search_field.text+deep_search_field.text+'.txt','a') as outfile:
		outfile.write(matches.text+'\n\n'+string)
	sound.play_effect('Shot')
	console.hud_alert('filed',duration=.1)
	#dialogs.alert('It is written')


def search_to_clipboard(sender):
	tbl=table
	all = tbl.data_source.items
	#string = ''.join(pairs[x[0]]+str(x)+'\n\n' for x in all)
	string = ''.join('## '+pairs[x[0]]+' '+str(x[1])+': '+str(x[2])+'\n\n'+str(x[3])+'\n\n' for x in all)
	#string = ''.join('**'+pairs[x[0]]+' '+str(x[1])+': '+str(x[2])+'**\n\n'+str(x[3])+'\n\n' for x in all)
	clipboard.set(matches.text+'\n\n'+string)
	#sound.play_effect('Shot')
	console.hud_alert('clipped',duration=.1)
	#dialogs.alert('It is coppied')


def zip_notes(sender):
	if dialogs.alert('Create?','this will zip all notes','Yes','No') ==1:
		time_stamp = datetime.datetime.today().strftime('%m_%d_%Y_%H:%M:%S')
		zf = zipfile.ZipFile(local+"Notes Backup {}.zip".format(time_stamp), "w")
		for dirname, subdirs, files in os.walk(local+"/Notes"):
			zf.write(dirname)
			for filename in files:
				zf.write(os.path.join(dirname, filename))
		zf.close()
		dialogs.hud_alert('Notes Zipped!')
	else:
		dialogs.hud_alert('Not zipped','error')


def view_video(sender):
	webbrowser.open('https://youtu.be/QWotciwYoGQ')
# END FUNCTIONS


#--- IMPLEMENTATION
# Getting ui elements and setting actions
bible = ui.load_view()
heading = bible['book_heading']
books = bible['books']
chapters = bible['chapters']
contents = bible['contents']
contents.font = ('TimesNewRomanPSMT',19)
testaments = bible['testaments']
testaments.action=test

thoughts_button = bible['btn_thoughts']
thoughts_button.action = selectionToThoughts

btn_copy = bible['btn copy']
btn_copy.action = selectionToClipboard
"""
#fav_button = left_pane['btn_fav']
#fav_button.action=save_selection
clip_button = thoughts_view['btn_copy']
clip_button.action=clip
translate_button =bible.left_button_items[3]
translate_button.action=translate
file_button = bible.left_button_items[0]
file_button.action=view_files
translation_label = bible['label_translation']
"""
search_button = bible['btn search']
search_button.action = show_search
search_close_button = bible['search']['btn close']
search_close_button.action = hide_search


#--- BOOK MARKS
book_marks = bible['bookmarks']
book_mark_button = bible['btn bookmark']
book_mark_button.action = add_mark
book_marks.action=load_mark

save_bookmarks_button=bible['btn save bookmarks']
save_bookmarks_button.action=save_bookmarks

clear_book_marks_button = bible['btn clear bookmarks']
clear_book_marks_button.action=clear_bookmarks
# END BOOKMARKS


#zip_button = top_pane['btn_zip']
#zip_button.action = zip_notes

"""
video_button = bible.right_button_items[2]
video_button.action = view_video
"""

deep_search_field = bible['deep search field']
deep_search_field.placeholder = 'Find'
deep_search_field.delegate = MyTextFieldDelegate()

#--- SEARCH ENGINE
search=bible['search']
#editor.apply_ui_theme(search)
search.alpha=0
search.hidden=True
#search.border_color = 'red'
search.border_width=2
search_field = search['search_field']
search_field.delegate = MyTextFieldDelegate()
search_clear_button = search['btn clear search']
search_clear_button.action = clear_search
forward_button = search['btn forward']
forward_button.action= forward_to_thoughts
text = search['textview2']
search_selection = search['textview2']
search_selection.text = "Romans 13: 8 Owe no man any thing, but to love one another: for he that loveth another hath fulfilled the law."
table= search['tableview1']
table.delegate = MyTableViewDelegate()
matches = search['matches']
save_all_button = search['btn save all']
save_all_button.action = search_to_file
copy_all_button = search['btn copy']
copy_all_button.action = search_to_clipboard
# END SEARCH ENGINE

# This lambda function is what allows me to pass arguments to a view's action function. This function is what makes it all work.
f = lambda sender: updates(sender,chapters.data_source,testaments)

# Quick and dirty query to preload a tableview with an sqlite record.
books.data_source.items = [x[0] for x in sqlite3.connect(database).execute('select n from key_english')]
books.data_source.action = f
# Display the bible with a hidden title bar and restrict its orientation to landscape.
bible.present('popover',hide_title_bar=True)
…End If
If… ?
Run the block if
style
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
dark
Bible Dark ?
Source Code
import ui,sqlite3,datetime,sound,console,clipboard,dialogs,re,editor,os,webbrowser,speech,fileinput,zipfile,webbrowser,json,editor

#--- VARIABLES
pairs={1: 'Genesis', 2: 'Exodus', 3: 'Leviticus', 4: 'Numbers', 5: 'Deuteronomy', 6: 'Joshua', 7: 'Judges', 8: 'Ruth', 9: '1 Samuel', 10: '2 Samuel', 11: '1 Kings', 12: '2 Kings', 13: '1 Chronicles', 14: '2 Chronicles', 15: 'Ezra', 16: 'Nehemiah', 17: 'Esther', 18: 'Job', 
19: 'Psalms', 20: 'Proverbs', 21: 'Ecclesiastes', 22: 'Song of Solomon', 23: 'Isaiah', 24: 'Jeremiah', 25: 'Lamentations', 26: 'Ezekiel', 27: 'Daniel', 28: 'Hosea', 29: 'Joel', 30: 'Amos', 31: 'Obadiah', 32: 'Jonah', 33: 'Micah', 34: 'Nahum', 35: 'Habakkuk', 36: 'Zephaniah', 37: 'Haggai', 38: 'Zechariah', 39: 'Malachi', 40: 'Matthew', 41: 'Mark', 42: 'Luke', 43: 'John', 44: 'Acts', 45: 'Romans', 46: '1 Corinthians', 47: '2 Corinthians', 48: 'Galatians', 49: 'Ephesians', 50: 'Philippians', 51: 'Colossians', 52: '1 Thessalonians', 53: '2 Thessalonians', 54: '1 Timothy', 55: '2 Timothy', 56: 'Titus', 57: 'Philemon', 58: 'Hebrews', 59: 'James', 60: '1 Peter', 61: '2 Peter', 62: '1 John', 63: '2 John', 64: '3 John', 65: 'Jude', 66: 'Revelation'}

local = os.path.join(os.path.expanduser("~"), "Documents")
database = local+'/bible-sqlite.db'
# I'd like to add a timestamp to notes, so:
time_stamp = datetime.datetime.today().strftime('%m_%d_%Y_%H:%M:%S')
# File name for our notes file (here for easy access)
save_file = 'favorites.txt'
thoughts_file='thoughts.txt'
bookmarks_file='bookmarks.txt'
translation='t_kjv'
backup='backup.txt'
fullscreen_preview=None


# We will load the following list into a list dialog
translations={"t_asv":"American Standard - ASV1901 (ASV)",
"t_bbe":"Bible in Basic English - (BBE)",
"t_dby":"Darby - (DBY)",
"t_kjv":"King James Version (KJV)",
"t_wbt":"Webster's Bible (WBT)",
"t_web":"World English Bible (WEB)",
"t_ylt":"Young's Literal Translation (YLT)"}
# END VARIABLES

images = {
	'0':'iob:share_32',
	'1':'iob:ios7_information_32',
	'2':'iob:ios7_videocam_32',
	'3':'iob:ios7_albums_outline_32',
	'4':'iob:camera_32',
	'5':'iob:calendar_24',
	'6':'iob:chatbox_working_24',
	'7':'iob:checkmark_circled_24',
	'8':'iob:clock_24',
	}

def create_assembly_folders():
	try:
		for folder in churches:
			document_directory=os.mkdir(folder)
	except:None


# Try to make a directory named 'Notes.' Do nothing if there is an exception error.
try:
	document_directory = os.mkdir(local+'/Notes')
except: None

"""
table_name: t_kjv
	records:
		b - book (int)
		c - chapter (int)
		v - verse (int)
		t - text (str)

table_name: key_english
	records:
		b - book (int)
		n - name (str)

table_name: bible_version_key
		id
		table
		abbreviation
	
American Standard - ASV1901 (ASV)
Bible in Basic English - (BBE)
Darby
King James Version (KJV)
Webster's Bible (WBT)
World English Bible (WEB)
Young's Literal Translation (YLT)
"""


#--- CLASSES			
# I will leave the results as a list so that I can load them into a tableview data source
# Textfield

# currently this class only backs up the thoughts text. hopefull it will bak up entire state of the app 


class MyTextFieldDelegate (object):
	def textfield_should_begin_editing(self, textfield):
		return True
	def textfield_did_begin_editing(self, textfield):
		pass
	def textfield_did_end_editing(self, textfield):
		if textfield.text != '':
			def show():
				search.hidden=False
				search.alpha=1
			ui.animate(show,.4)
			try:
				con = sqlite3.connect(database)
				cur = con.cursor()			
				substring= textfield.text
				sub_query="select b,c,v,t from {} where t like '%{}%'".format(translation,substring)
				sub_all=[x for x in cur.execute(sub_query)]
				table.data_source = ui.ListDataSource(sub_all)
				table.reload()
				matches.text=str(len(sub_all))
				#table.reload_data()
			except:
				None
	def textfield_should_return(self, textfield):
		textfield.end_editing()
		return True
	def textfield_should_change(self, textfield, range, replacement):
		return True
	def textfield_did_change(self, textfield):
		pass

#Textview
class MyTextViewDelegate (object):
	def textview_should_begin_editing(self, textview):
		return True
	def textview_did_begin_editing(self, textview):
		pass
	def textview_did_end_editing(self, textview):
		pass
	def textview_should_change(self, textview, range, replacement):
		return True
	def textview_did_change(self, textview):
		return True
	def textview_did_change_selection(self, textview):
		pass

#Tableview
class MyTableViewDelegate (object):
	def tableview_did_select(self, tableview, section, row):
		# Called when a row was selected.
		item = tableview.data_source.items[row]
		# Search results formatting
		search_selection.text =  '**'+str(pairs[item[0]])+' '+str(item[1])+': '+str(item[2])+'**'+'\n\n'+str(item[3])

	def tableview_did_deselect(self, tableview, section, row):
		# Called when a row was de-selected (in multiple selection mode).
		pass

	def tableview_title_for_delete_button(self, tableview, section, row):
		# Return the title for the 'swipe-to-***' button.
		return 'Delete'


# CLASSES
class MyTableViewDelegate2 (object):
	def tableview_did_select(self, tableview, section, row):
		# Called when a row was selected.
		cell = tableview.data_source.items[row]
		set_view_text(str(cell))
		header_label.text = tableview.data_source.items[row].strip('.txt').capitalize()
		#sound.play_effect('ui:click2')

	def tableview_did_deselect(self, tableview, section, row):
		# Called when a row was de-selected (in multiple selection mode).
		pass

	def tableview_title_for_delete_button(self, tableview, section, row):
		# Return the title for the 'swipe-to-***' button.
		return 'Trash it'
# END CLASSES

#--- FUNCTIONS
# closes the superview of the sender
def close(sender):
	sender.superview.superview.close()
	speech.stop()


# save text in a view to the clipboard
def clip(sender):
	clipboard.set(thought_bubble.text)
	console.alert('Saved to Clipboard')


# open a list dialog
def translate(sender):
	global translation
	show=dialogs.list_dialog('Translations',[trans for trans in translations])
	translation=show
	try:
		translation_label.text = translations[translation]
	except: None

	
# open the IOS share sheet
def share(sender):
	dialogs.share_text(thought_bubble.text)


# load sqlite3 query into a tableview as a result of a segmented control action
def test(sender):
	con = sqlite3.connect(database)
	cursor=con.cursor()
	# A query to get all old testament book names in the 'key_english' table 
	ot_query = 'select n from key_english where b < 40'
	ot_bks = [x[0] for x in cursor.execute(ot_query)]
	
	# A query to get all new testament book names in the 'key_english' table 
	nt_query = 'select n from key_english where b >= 40'
	nt_bks = [x[0] for x in cursor.execute(nt_query)]
	
	selected_testament = sender.segments[sender.selected_index]
	
	if selected_testament=='Old':
		books.data_source.items=ot_bks
	
	elif selected_testament=='New':
		books.data_source.items= nt_bks


# Updates the table and text views
def updates(*args):
	# Connect to the sqlite database and create a cursor to query it with
	con = sqlite3.connect(database)
	cursor=con.cursor()
	# Three argument parameters (all tanleviews) that were passed in using a lambda function.
	tbl_books = args[0]
	tbl_chapters = args[1]
	control_testaments = args[2]
	
	# A query to get all book names in the 'key_english' table
	all_bks_query = 'select n from key_english'
	all_bks = [x[0] for x in cursor.execute(all_bks_query)]
	
	# Store tableview selections
	selected_book = tbl_books.items[tbl_books.selected_row]
	#selected_chap = tbl_chapters.items[tbl_chapters.selected_row]['title'] editorial #v 1.2
	selected_chap = tbl_chapters.items[tbl_chapters.selected_row] #editorial v 1.3
	#selected_testament = control_testaments.segments[control_testaments.selected_index]
	
	
	# Select book from the key_english table where the name = the selected book/cell of a tableview
	num_query = "select b from key_english where n='{}'".format(selected_book)
	bk_num=[x for x in cursor.execute(num_query)][0][0]
	
	c = selected_chap # unnecessary perhaps but using 'c' is shorter.
	
	# Select chapter,verse,text from the t_kjv table where book = book number (tableview) and chapter = selected chapter
	txt_query = "select c,v,t from '{}' where b = '{}' AND c = '{}'".format(translation,bk_num,c)
	txt = [row for row in cursor.execute(txt_query)]
	# Format the text as -- ''+chapter+text -- ('' can be replaced with whatever prefix you want)
	txt_formatted = "\n".join("{} {}: {}\n".format('',c,t) for b,c,t in txt)
	
	# If the formatted text is an empty string, set the contents textview to a string
	# This is a quick fix if a user selects a chapter in a book that doesn't exist for that book
	if txt_formatted=='':
		contents.text = 'Chapter does not exist'
	
	# Otherwise, set the contents textview to the formatted text
	else:
		contents.text = txt_formatted
	# Set the heading label to the selected book plus the selected chapter (as a string)
	heading.text=selected_book+' '+str(selected_chap)


#	Save text/selected text in a textview to a file
def save_selection(sender):
	'''saves text/selected text in a textview to a file. If no text is selected, the entire text is saved.'''
	# Get the beginning of the textview selection
	beg= contents.selected_range[0]
	# Get the end of the textview selection
	end = contents.selected_range[1]
	# Get the entire text in the textview
	txt = contents.text
	# If text is selected (if there is a substring from beginning to end)...
	with open(local+'/Notes/'+save_file,'a') as outfile:
		if txt[beg:end] != '':
			# write the text to a file with a timestamp, the heading lable text, and the selected text.
			outfile.write('\n'+time_stamp+'\n'+heading.text+'\n\n'+txt[beg:end]+'\n')
		# Otherwise...
		else:
			# write the entire text to the file.
			outfile.write('\n'+time_stamp+'\n'+heading.text+'\n\n'+txt+'\n')
	# Play a sound
	#sound.play_effect('digital:ThreeTone2')
	# Alert the user that fhe file has been saved to the file.
	console.alert('Saved to {}'.format(save_file))

# Same logic as save_selection
def selectionToClipboard(sender):
	beg= contents.selected_range[0]
	end = contents.selected_range[1]
	txt = contents.text
	if txt[beg:end] != '':
		clipboard.set(clipboard.get()+'\n'+"**"+heading.text+"**"+'\n\n'+txt[beg:end]+'\n\n')
	else:
		clipboard.set(clipboard.get()+'\n'+"**"+heading.text+"**"+'\n\n'+txt+'\n\n')
	console.hud_alert('appended',duration=.1)
		

def selectionToThoughts(sender):
	console.hud_alert('captured',duration=.1)
	#sound.play_effect('rpg:Creak3')
	beg= contents.selected_range[0]
	end = contents.selected_range[1]
	txt = contents.text
	if txt[beg:end] != '':
		editor.insert_text("## "+heading.text+'\n\n'+txt[beg:end]+'\n\n')
		#editor.insert_text("**"+heading.text+"**"+'\n\n'+txt[beg:end]+'\n\n')
	else:
		editor.insert_text("## "+heading.text+'\n\n'+txt+'\n\n')
		#editor.insert_text("**"+heading.text+"**"+'\n\n'+txt+'\n\n')


# Shows the search window
def show_search(sender):
	def show():
		search.hidden=False
		search.alpha=1
	ui.animate(show,.4)

		
# Hides the search window
def hide_search(sender):
	def hide():
		search.alpha=0
	ui.animate(hide,.4)
	#search.present('sheet')
	#search.hidden=True

	
def clear_search(sender):
	search_field.text=''


def forward_to_thoughts(sender):
	editor.insert_text('\n\n'+search_selection.text+'\n')
	#editor.insert_text('\n\n'+'## '+search_selection.text+'\n')
	#sound.play_effect('rpg:BookFlip2')


# File name for our thoughts file.
def choose_file():
	global thoughts_file
	file_select= dialogs.list_dialog('Select A File',['New']+os.listdir(local+'/Notes'))
	if file_select=='New':
		thoughts_file = dialogs.input_alert('Name your thoughts file')+'.txt'
	elif file_select==None:
		pass
	else:
		thoughts_file= file_select


def view_files(sender):
	global thoughts_file
	file_select= dialogs.list_dialog('Select A File',['New']+os.listdir(local+'/Notes'))
	if file_select=='New':
		thoughts_file = dialogs.input_alert('Name your thoughts file')+'.txt'
	elif file_select==None:
		pass
	else:
		thoughts_file= file_select
	thoughts_title.text = thoughts_file


def add_mark(sender):
	# Store tableview selections
	# Connect to the sqlite database and create a cursor to query it with
	con = sqlite3.connect(database)
	cursor=con.cursor()
	selected_book = books.data_source.items[books.data_source.selected_row]
	#selected_chap = chapters.data_source.items[chapters.data_source.selected_row]['title']
	selected_chap = chapters.data_source.items[chapters.data_source.selected_row][0]
	#selected_testament = control_testaments.segments[control_testaments.selected_index]	
	# Select book from the key_english table where the name = the selected book/cell of a tableview
	num_query = "select b from key_english where n='{}'".format(selected_book)
	bk_num=[x for x in cursor.execute(num_query)][0][0]
	txt_query = "select c,v,t from '{}' where b = '{}' AND c = '{}'".format(translation,bk_num,selected_chap)
	txt = [row for row in cursor.execute(txt_query)]
	# Format the text as -- ''+chapter+text -- ('' can be replaced with whatever prefix you want)
	txt_formatted = "\n".join("{} {}: {}\n".format('',c,t) for b,c,t in txt)
	try:
		if selected_chap:
			book_marks.segments = book_marks.segments+tuple([selected_book+' '+str(selected_chap)+'\n'+txt_formatted])
	except: None


def load_mark(sender):
	txt=sender.segments[sender.selected_index]
	if txt=='':
		contents.text='empty'
	else:
		contents.text=txt
	heading.text = 'Bookmark'
	#heading.text=selected_book+' '+str(selected_chap)


def save_bookmarks(sender):
	bookmarks_file='bookmark: '+'test'+'.txt'
	txt=book_marks.segments
	for x in txt:
		with open(local+'/Notes/'+bookmarks_file,'a',encoding='utf-8')	as outfile:
			outfile.write(time_stamp+'\n'+str(x)+'\n')
	#sound.play_effect('rpg:BookFlip2')
	console.alert('Saved to {}'.format(bookmarks_file))


def clear_bookmarks(sendr):
	book_marks.segments=['']


def search_to_file(sender):
	tbl=table
	all = tbl.data_source.items
	string = ''.join('**'+pairs[x[0]]+' '+str(x[1])+': '+str(x[2])+'**\n\n'+str(x[3])+'\n\n' for x in all)
	with open(local+'/Notes/'+'search: '+search_field.text+deep_search_field.text+'.txt','a') as outfile:
		outfile.write(matches.text+'\n\n'+string)
	sound.play_effect('Shot')
	console.hud_alert('filed',duration=.1)
	#dialogs.alert('It is written')


def search_to_clipboard(sender):
	tbl=table
	all = tbl.data_source.items
	#string = ''.join(pairs[x[0]]+str(x)+'\n\n' for x in all)
	string = ''.join('## '+pairs[x[0]]+' '+str(x[1])+': '+str(x[2])+'\n\n'+str(x[3])+'\n\n' for x in all)
	#string = ''.join('**'+pairs[x[0]]+' '+str(x[1])+': '+str(x[2])+'**\n\n'+str(x[3])+'\n\n' for x in all)
	clipboard.set(matches.text+'\n\n'+string)
	#sound.play_effect('Shot')
	console.hud_alert('clipped',duration=.1)
	#dialogs.alert('It is coppied')


def zip_notes(sender):
	if dialogs.alert('Create?','this will zip all notes','Yes','No') ==1:
		time_stamp = datetime.datetime.today().strftime('%m_%d_%Y_%H:%M:%S')
		zf = zipfile.ZipFile(local+"Notes Backup {}.zip".format(time_stamp), "w")
		for dirname, subdirs, files in os.walk(local+"/Notes"):
			zf.write(dirname)
			for filename in files:
				zf.write(os.path.join(dirname, filename))
		zf.close()
		dialogs.hud_alert('Notes Zipped!')
	else:
		dialogs.hud_alert('Not zipped','error')


def view_video(sender):
	webbrowser.open('https://youtu.be/QWotciwYoGQ')
# END FUNCTIONS


#--- IMPLEMENTATION
# Getting ui elements and setting actions
bible = ui.load_view()
heading = bible['book_heading']
books = bible['books']
chapters = bible['chapters']
contents = bible['contents']
contents.font = ('TimesNewRomanPSMT',19)
testaments = bible['testaments']
testaments.action=test

thoughts_button = bible['btn_thoughts']
thoughts_button.action = selectionToThoughts

btn_copy = bible['btn copy']
btn_copy.action = selectionToClipboard
"""
#fav_button = left_pane['btn_fav']
#fav_button.action=save_selection
clip_button = thoughts_view['btn_copy']
clip_button.action=clip
translate_button =bible.left_button_items[3]
translate_button.action=translate
file_button = bible.left_button_items[0]
file_button.action=view_files
translation_label = bible['label_translation']
"""
search_button = bible['btn search']
search_button.action = show_search
search_close_button = bible['search']['btn close']
search_close_button.action = hide_search


#--- BOOK MARKS
book_marks = bible['bookmarks']
book_mark_button = bible['btn bookmark']
book_mark_button.action = add_mark
book_marks.action=load_mark

save_bookmarks_button=bible['btn save bookmarks']
save_bookmarks_button.action=save_bookmarks

clear_book_marks_button = bible['btn clear bookmarks']
clear_book_marks_button.action=clear_bookmarks
# END BOOKMARKS


#zip_button = top_pane['btn_zip']
#zip_button.action = zip_notes

"""
video_button = bible.right_button_items[2]
video_button.action = view_video
"""

deep_search_field = bible['deep search field']
deep_search_field.placeholder = 'Find'
deep_search_field.delegate = MyTextFieldDelegate()

#--- SEARCH ENGINE
search=bible['search']
#editor.apply_ui_theme(search)
search.alpha=0
search.hidden=True
#search.border_color = 'red'
search.border_width=2
search_field = search['search_field']
search_field.delegate = MyTextFieldDelegate()
search_clear_button = search['btn clear search']
search_clear_button.action = clear_search
forward_button = search['btn forward']
forward_button.action= forward_to_thoughts
text = search['textview2']
search_selection = search['textview2']
search_selection.text = "Romans 13: 8 Owe no man any thing, but to love one another: for he that loveth another hath fulfilled the law."
table= search['tableview1']
table.delegate = MyTableViewDelegate()
matches = search['matches']
save_all_button = search['btn save all']
save_all_button.action = search_to_file
copy_all_button = search['btn copy']
copy_all_button.action = search_to_clipboard
# END SEARCH ENGINE

# This lambda function is what allows me to pass arguments to a view's action function. This function is what makes it all work.
f = lambda sender: updates(sender,chapters.data_source,testaments)

# Quick and dirty query to preload a tableview with an sqlite record.
books.data_source.items = [x[0] for x in sqlite3.connect(database).execute('select n from key_english')]
books.data_source.action = f
# Display the bible with a hidden title bar and restrict its orientation to landscape.
bible.present('popover',hide_title_bar=True)
…End If