#!/usr/bin/python

import gtk

import demo
import xesam
from xesam.client import *
from xesam.ui import *
from xesam.query import *

running_search = None

query = CompositeQuery()
full_text = FullTextClause ()
full_text_value = StringValue("")
full_text.set_value(full_text_value)
query.set_clause (full_text)

def spawn_search (entry, model, session):
	global running_search
	txt = entry.get_text()
	
	if running_search:
		# This should also clear the model
		running_search.close()
		
	if txt == None or len(txt) == 0:
		xesam.debug ("Empty search field. Ignoring.")
		return
	
	#
	# Comment this section in to use composite queries
	# instead of userQuery-queries. Beagle adaptor only
	# supports composite queries atm.
	#
	#global full_text_value
	#global query
	#full_text_value.set (txt)
	#running_search = Search (session, query)
	
	running_search = UserSearch (session, txt)
	
	model.set_search (running_search)
	running_search.start()

session = Session()
session.set_property ("hit-fields", ["xesam:url", "xesam:mimeType", "xesam:title"])
session.set_property ("search-live", True) # Needed for Beagle
model = HitPagerModel (session)
view = HitView (model)
scroll = gtk.ScrolledWindow()
entry = gtk.Entry()
vbox = gtk.VBox()
browser_box = gtk.HBox()
button_next = gtk.Button (stock=gtk.STOCK_GO_FORWARD)
button_prev = gtk.Button (stock=gtk.STOCK_GO_BACK)
window = gtk.Window()

scroll.set_policy (gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
view.set_hit_message (
"""<b>%(xesam:title)s</b>       %(id)s
<small>Url: <i>%(xesam:url)s</i>
Mime: <i>%(xesam:mimeType)s</i></small>"""
)

button_next.set_sensitive (False)
button_prev.set_sensitive (False)

entry.connect ("activate", spawn_search, model, session)
window.connect ("destroy", gtk.main_quit)
button_next.connect ("clicked", lambda btn : model.next_page())
button_prev.connect ("clicked", lambda btn : model.previous_page())
model.connect ("notify::has-next-page",
				lambda x, y : button_next.set_sensitive(model.get_property("has-next-page")))
model.connect ("notify::has-previous-page",
				lambda x, y : button_prev.set_sensitive(model.get_property("has-previous-page")))

scroll.add(view)
vbox.pack_start (entry, False, False)
vbox.pack_start (scroll, True, True)
vbox.pack_start (browser_box, False, False)

browser_box.pack_end (button_next, False, False)
browser_box.pack_end (button_prev, False, False)

window.add (vbox)

window.show_all ()
window.resize (400, 600)

gtk.main()


