#! /usr/bin/env python

import sys, os
from zeitgeist.datamodel import Event, Subject, ResultType, TimeRange
from zeitgeist.client import ZeitgeistDBusInterface

USAGE = \
"""Talis is a command line tool to search your history.
USAGE:
	talis [options] <enter search terms here>

OPTIONS:
	--mode=, -m=		MODE
	--offset=, -o=		Offset into result set
	--hits=, -h=		Max number of hits to return
	--relevancies, -r	With relevancies

MODES:
	LeastPopularActor
	LeastPopularSubjects
	LeastRecentActor
	LeastRecentEvents
	LeastRecentSubjects
	MostPopularActor
	MostPopularSubjects
	MostRecentActor
	MostRecentEvents
	MostRecentSubjects
	Relevancy (default)
"""

if len(sys.argv) <= 1:
	print USAGE
	raise SystemExit(1)

offset = 0
maxhits = 10
mode = 100
mode_string = "Relevancy"
query = ""
relevancy_mode = False
for i in range(1, len(sys.argv)):
	if sys.argv[i].startswith("--mode=") or sys.argv[i].startswith("-m="):
		mode_string = sys.argv[1].replace("--mode=", "").replace("-m=", "").strip()
		if mode_string == "Relevancy":
			mode = 100
		else:
			mode = getattr(ResultType, mode_string)
	elif sys.argv[i].startswith("--offset=") or sys.argv[i].startswith("-o="):
		offset = int(sys.argv[i].replace("--offset=", "").replace("-o=", "").strip())
	elif sys.argv[i].startswith("--hits=") or sys.argv[i].startswith("-h="):
		maxhits = int(sys.argv[i].replace("--hits=", "").replace("-h=", "").strip())
	elif sys.argv[i] in ["--relevancies", "-r"]:
		relevancy_mode = True
	else:
		query += " " + sys.argv[i]
		
query = query.strip()

fts = ZeitgeistDBusInterface().get_extension("Index", "index/activity")
if relevancy_mode:
	results, relevancies, count = fts.SearchWithRelevancies(query, TimeRange.always(), [], 2, offset, maxhits, mode)
else:
	results, count = fts.Search(query, TimeRange.always(), [], offset, maxhits, mode)

if len(results) == 0:
    print "No hits for '%s'" % query
    raise SystemExit(0)

print "%s-%s of %s hits for '%s'. Sorted by '%s':" % (offset+1,
        len(results)+offset, count, query, mode_string)

i = offset+1
events = map(Event, results)
for event in events:
	for subject in event.subjects:
		if relevancy_mode:
			print " %s. %s\t(%.2f)" % (i, subject.uri, relevancies[i-1])
		else:
			print " %s. %s" % (i, subject.uri)
		i += 1
