# Bryan Schumaker (11/12/2010)

import libsaria
from libsaria import path
from libsaria.sources import playlist
from libsaria import version
from libsaria import callbacks
import libsaria.xm as xml

add_child = xml.add_child
add_text  = xml.add_text
get_attrs = libsaria.sources.library.get_attrs
file_id   = path.file_id
lib_file  = "library"
vers      = "%s.%s" % (version.__major__, version.__minor__)
if version.__dev__ == True:
	lib_file = lib_file + "-dev"
lib_file += ".xml"
lib_file  = path.join(path.saria_dir(), lib_file)

xml_children = xml.children
xml_child    = xml.child
xml_attrs    = xml.attributes

#######################################
# Generic encode and decode functions #
#######################################

def decode_attr(attr):
	child = xml.child(attr)
	return (attr.nodeName, child.data.strip())

def encode_attr(doc, node, attr, value):
	child = add_child(doc, node, attr)
	add_text(doc, child, value)

def encode_track(doc, node, id):
	filepath, like, count = get_attrs(id, "filepath", "like", "count")
	if (like == None) and (count == 0):
		return
	child = add_child(doc, node, "track", {"like":like, "count":count})
	add_text(doc, child, filepath)

##################################
# xspf encode / decode functions #
##################################

def decode_xspf_track(location):
	file = xml.child(location).data.strip()
	if file[:7] == "file://":
		id = path.file_id(file[7:])
		playlist.add_ids([id])

def decode_xspf(child):
	tlist = xml.child(child)
	playlist.reset()
	for node in xml.children(tlist):
		try:
			loc = xml.get_elements(node, "location")[0]
			decode_xspf_track(loc)
		except:
			pass
	playlist.save()
	callbacks.load_playlist()

def encode_xspf(doc, node, id):
	filepath = get_attrs(id, "filepath")[0]
	track    = add_child(doc, node, "track")
	location = add_child(doc, track, "location")
	add_text(doc, location, "file://%s" % filepath)


#############################################
# Control will enter the export module here #
#############################################

def save_playlist(filepath):
	file, ext = path.splitext(filepath)
	if ext != ".xml":
		filepath+=".xml"

	doc   = xml.new()
	child = add_child(doc, doc, "playlist", {"version":1, "xmlns":"http://xspf.org/ns/0/"})
	tlist = add_child(doc, child, "trackList")

	for id in playlist.list_ids():
		encode_xspf(doc, tlist, id)

	fout = open(filepath, 'w')
	fout.write(doc.toprettyxml())
	fout.close()
	print "Wrote playlist to: %s" % filepath

def import_xml(file):
	fin   = open(file)
	doc   = xml.parse(fin)
	child = xml.child(doc)
	if child.nodeName == "playlist":
		decode_xspf(child)
