# Bryan Schumaker (8/15/2010)

# Lazy loaded modules
path  = None
imp   = None

# Runtime variables
p_dir = None
loaded = dict()

# Function variables
install     = None
load_all    = None
load_plugin = None


def init():
	global path
	global p_dir
	if path == None:
		from libsaria import path
	if p_dir == None:
		p_dir = path.plugin_dir()

def quit():
	global loaded
	for mod in loaded:
		try:
			loaded[mod].stop()
		except:
			pass


def install_once(filepath):
	global install
	init()
	install = install_rest
	install(filepath)
def install_rest(filepath):
	global p_dir
	global path
	split = filepath.rsplit(path.sep, 1)
	file = split[len(split)-1]
	dest = path.join(p_dir, file)
	path.cp(filepath, dest)
	split = path.splitext(file)
	if split[len(split)-1] == ".py":
		name = split[0]
		load_plugin(name, dest)
install = install_once


def load_all_once():
	global load_all
	init()
	load_all = load_all_rest
	load_all()
def load_all_rest():
	global load_plugin
	global path
	global p_dir
	for file in path.ls(p_dir):
		split = path.splitext(file)
		if split[len(split)-1] == ".py":
			load_plugin(split[0], path.join(p_dir, file))
load_all = load_all_once


def load_plugin_once(name, file):
	global load_plugin
	global imp
	import imp
	load_plugin = load_plugin_rest
	load_plugin(name, file)
def load_plugin_rest(name, file):
	global imp
	global path
	global loaded

	if name in loaded:
		mod = loaded[name]
		if hasattr(mod, "stop"):
			loaded[name].stop()
		del globals()[name]

	try:
		mod = imp.load_source(name, file)
	except Exception, e:
		print "Error loading plugin: %s" % file
		print e

	try:
		if mod.check_version() == False:
			print "Error: plugin %s requires a different version" % name
			return
	except:
		print "Warning: plugin %s doesn't check versions" % name

	try:
		globals()[name] = mod
		loaded[name] = mod
		mod.start()
	except Exception, e:
		print "Error starting plugin: %s" % file
		print e
load_plugin = load_plugin_once
