import subprocess
import sys
import Alfred
 
handler = Alfred.Handler(args=sys.argv)
 
raw_query = handler.query
 
if " " in raw_query:
	query = raw_query.split(" ")
	lib_name = query[0]
	lib_version = query[1]
else:
	lib_name = raw_query
	lib_version = None
 
if lib_version is not None:
	sprocess = subprocess.Popen(["haxelib", "install", lib_name, lib_version], stdout=subprocess.PIPE)
else:
	sprocess = subprocess.Popen(["haxelib", "install", lib_name], stdout=subprocess.PIPE)
 
output = sprocess.stdout.read()
 
was_downloading = False
 
if "Downloading" in output.split("\n")[0]:
	was_downloading = True
 
sprocess.wait()
 
if lib_version is not None:
	version = " %s" % lib_version
else:
	version = ""
 
if was_downloading:
	print "Installed %s%s" % (lib_name, version)
else:
	print "%s: %s" % (lib_name, output)