import sys
import subprocess
import Alfred
 
handler = Alfred.Handler(args=sys.argv)
 
if " " in handler.query:
	query = handler.query.split(" ")
 
	lib_name = query[0]
	lib_version = query[1]
else:
	lib_name = handler.query
	lib_version = None
 
raw_result = subprocess.Popen(["haxelib", "search", lib_name], stdout=subprocess.PIPE).stdout.read()
 
haxelib_result = raw_result.split("\n")
 
# remove blank line
haxelib_result = haxelib_result[0:-1]
 
number_of_libs = haxelib_result[-1].split(" ")[0]
 
# remove number of libraries
haxelib_result = haxelib_result[0:-1]
 
if lib_version is None:
	for result in haxelib_result:
		# TODO: add description to subtitle
		item = Alfred.Item(title=result, subtitle="Install %s" % result, uid=result, arg=result)
		handler.add_item(item)
else:
	if lib_name in haxelib_result:
		item = Alfred.Item(title=lib_name, subtitle="Install %s version %s" % (lib_name, lib_version), uid=lib_name, arg="%s %s" % (lib_name, lib_version))
		handler.add_item(item)
 
handler.add_new_item(title="%s libraries found" % number_of_libs)
 
handler.push()