# Bryan Schumaker (5 / 21 / 2011)

import re
import string
import library

lib_index = dict()
all_ids   = set()
matching  = set()
search    = re.search

space_ord = ord(" ")
stripc    = u"\"#$%&'*+<=>@[]^`{|}~.?!"
splitc    = u"-\/,:;()_~+"
upper     = string.uppercase
lower     = string.lowercase

# Create a translation table for formatting text
ttable = dict((ord(c), None) for c in stripc)
splitt = dict((ord(c), space_ord) for c in splitc)
lowert = dict((ord(c), ord(lower[i])) for i, c in enumerate(upper))
for t in (splitt, lowert):
	for c in t:
		ttable[c] = t[c]

def reset():
	global lib_index
	global all_ids
	lib_index = dict()
	all_ids   = set()

def format(text):
	return text.translate(ttable).split()

def add_to_index(id, text):
	for word in format(text):
		if lib_index.get(word) == None:
			lib_index[word] = set([id])
		else:
			lib_index[word].add(id)

def add_tracks(tracks):
	for id, track in tracks.iteritems():
		all_ids.add(id)
		add_to_index(id, track.artist)
		add_to_index(id, track.album)
		add_to_index(id, track.title)

def reindex():
	global matching
	reset()
	for src, tracks in library.lib_dict.iteritems():
		add_tracks(tracks)
	matching = all_ids

def is_visible(id):
	return id in matching

def num_visible():
	return len(matching)

def do_filter(terms):
	if len(terms) == 0:
		return all_ids

	get = lib_index.get
	results = dict((t, set()) for t in terms)
	for key in lib_index.keys():
		for term in terms:
			if search(term, key):
				results[term].update(get(key))

	visible = set()
	for i, t in enumerate(terms):
		if i == 0:
			visible.update(results[t])
		else:
			visible.intersection_update(results[t])
	return visible

def filter(text):
	global matching
	text  = unicode(text)
	terms = format(text)
	matching = do_filter(terms)
	return matching
