# Bryan Schumaker (8/7/2010)

import libsaria
from libsaria import path
import cPickle as pickle
plugin = None
export = None

dev = ""
if libsaria.__dev__ == True:
	dev = "-dev"

PROTO = pickle.HIGHEST_PROTOCOL

def save(item, file, ext=".pickle"):
	file = "%s%s%s" % (path.join(path.saria_dir(),file), dev, ext)
	savefile(item, file)

def savefile(item, file):
	f = open(file, 'w')
	p = pickle.Pickler(f, PROTO)
	p.dump(item)
	f.close()

def load(file, ext=".pickle"):
	file = "%s%s%s" % (path.join(path.saria_dir(),file), dev, ext)
	return loadfile(file)

def loadfile(file):
	if path.exists(file) == False:
		return
	f = open(file)
	data = f.read()
	item = pickle.loads(data)
	f.close()
	return item

def open_plugin(file):
	global plugin
	if plugin == None:
		from libsaria import plugin
	plugin.install(file)

def open_xml(file):
	global export
	if export == None:
		import export
	export.import_xml(file)

def open_music(file):
	try:
		from libsaria.sources import file as file_source
		file_source.load_file(file)
	except Exception, e:
		print e

mapping = {".py":open_plugin, ".xml":open_xml}
def universal_open(file):
	file = file.replace("%20", " ")
	file = file.replace("%22", "\"")
	if path.is_dir(file):
		libsaria.sources.new_source(file)
		return
	base, ext = path.splitext(file)
	func = mapping.get(ext, open_music)
	func(file)
