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", "list"], stdout=subprocess.PIPE).stdout.read()
 
raw_libs = raw_result.split("\n")
 
# remove blank line
raw_libs = raw_libs[0:-1]
 
libs = dict()
 
# get all installed libs with versions
for lib in raw_libs:
	lib_splitted = lib.split(":")
 
	name = lib_splitted[0]
	raw_versions = lib_splitted[1]
 
	raw_versions_splitted = raw_versions.split(" ")
 
	set_version = ""
	version_list = list()
 
	for raw_version in raw_versions_splitted:
		if raw_version != "" and not "[" in raw_version:
			version_list.append(raw_version)
		else:
			if raw_version != "" and not "dev" in raw_version:
				set_version = raw_version[1:-1]
			elif "dev" in raw_version:
				set_version = "dev"
 
	libs[name] = {"actual_version": set_version, "other": version_list}
 
if lib_version is None:
	for lib in libs.iterkeys():
		if lib_name in lib:
			other_lib_count = len(libs[lib]["other"])
			subtitle = "" if not other_lib_count > 0 else "%s other versions installed." % other_lib_count
			handler.add_new_item(title="%s [%s]" % (lib, libs[lib]["actual_version"]), subtitle=subtitle, uid=lib, arg=lib)
else:
	if lib_name in libs.iterkeys():
		for version in libs[lib_name]["other"]:
			if lib_version in version:
				handler.add_new_item(title="%s: version %s" % (lib_name, version), uid=lib_name, arg="%s %s" %(lib_name, lib_version))
 
handler.push()