# Bryan Schumaker (11/24/2010)

import ocarina
gtk   = ocarina.gtk
Label = gtk.Label
prefs = ocarina.libsaria.prefs
get_pref = prefs.get_pref
set_pref = prefs.set_pref

contents = dict()

body = None
page_header = None
page_footer = None

class Page(gtk.VBox):
	def __init__(self, content):
		gtk.VBox.__init__(self)
		self.content    = content
		self.attrs      = content.__dict__
		self.vis_func   = self.attrs.get("visible", None)
		self.invis_func = self.attrs.get("invisible", None)
		self.show()

	def filter(self, text):
		self.content.filter(text)

	def reset(self):
		self.content.reset()

	def goto(self):
		self.content.goto()

	def visible(self):
		self.pack_start(page_header, False, False)
		self.pack_start(self.content, True, True)
		self.pack_start(page_footer, False, False)
		if self.vis_func:
			self.vis_func()

	def invisible(self):
		self.remove(page_header)
		self.remove(self.content)
		self.remove(page_footer)
		if self.invis_func:
			self.invis_func()

def init(window):
	global body
	global page_header
	global page_footer

	import header
	import footer
	from components import entry
	page_header = header.header
	page_footer = footer.footer

	body = gtk.Notebook()
	body.set_tab_pos(gtk.POS_LEFT)
	body.show()

def init_page(page_name):
	page  = prefs.init_pref("ocarina.body.page", page_name)
	child = contents.get(page, None)
	if child == None:
		child = contents.get(page_name)
	num   = body.page_num(child)
	body.set_current_page(num)
	child.visible()
	body.connect("switch-page", switch_page)

def add_page(name, content):
	label = Label(name)
	label.set_angle(90)
	page  = Page(content)
	contents[name] = page
	body.append_page(page, label)
	body.set_tab_label_packing(page, True, True, gtk.PACK_START)

def remove_page(name):
	page = contents.get(name, None)
	if page == None:
		return
	n = body.page_num(page)
	if n == body.get_current_page():
		body.set_current_page(n - 1)
	body.remove_page(n)
	del contents[name]

def switch_page(notebook, page, pagenum):
	cur_num = body.get_current_page()
	child   = body.get_nth_page(cur_num)
	next_pg = body.get_nth_page(pagenum)
	next    = None
	for name, item in contents.iteritems():
		if item == next_pg:
			next = name
	set_pref("ocarina.body.page", next)
	child.invisible()
	next_pg.visible()

def cur_page_filter(text):
	cur_num = body.get_current_page()
	page = body.get_nth_page(cur_num)
	page.filter(text)

def cur_page_reset():
	cur_num = body.get_current_page()
	page = body.get_nth_page(cur_num)
	page.reset()

def cur_page_goto():
	cur_num = body.get_current_page()
	page = body.get_nth_page(cur_num)
	page.goto()
