# Bryan Schumaker (11/27/2010)

import ocarina
from ocarina import footer
from ocarina.components import image
from ocarina.components import label
import re

libsaria = ocarina.libsaria
from libsaria import web
from libsaria import xm
from libsaria import cache

__NAME__ = "Lyrics"
gtk = ocarina.gtk

lyrics = gtk.ScrolledWindow()
page   = gtk.HBox(False, 5)
text   = gtk.TextView()
buffer = text.get_buffer()

lyrics.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)

page.pack_start(image.AlbumArt(), False, False)

text.set_editable(False)
lyrics.add(text)
page.pack_start(lyrics)

page.show_all()

url = "http://lyrics.wikia.com/api.php?"

def decode_line(line):
	string = ""
	for c in line.split(";"):
		if len(c) == 0:
			continue
		try:
			val = int(c[2:])
			string += chr(val)
		except:
			pass
	return string

def decode(file, code):
	lines = []
	for line in code:
		lines.append(decode_line(line))
	string = "\n".join(lines)
	file.write(string)

def parse_full(file, lyrics):
	req = web.Url(lyrics)
	res = None
	for line in req.open():
		if re.match("<div class=\'lyricbox\'>(.*?)", line):
			res = line
	split = res.split("</div>")
	code  = split[len(split) - 1]
	decode(file, code.split("<br />"))

def parse(file, res):
	doc      = xm.parse(res)
	result   = xm.child(doc)
	url_node = xm.get_elements(result, "url")[0]
	lyrics   = xm.child(url_node).data
	parse_full(file, lyrics)

def fetch_lyrics(file, artist, title):
	req = web.Url(url)
	req["artist"] = artist
	req["song"]   = title
	req["fmt"]    = "xml"
	try:
		parse(file, req.open())
	except:
		return False
	return True

def set_lyrics(filepath):
	artist, title = libsaria.sources.get_attrs("artist", "title")
	cached = cache[artist]
	file   = cached.get("%s.txt" % title, fetch_lyrics, artist, title)
	if file != None:
		fin    = open(file)
		buffer.set_text(fin.read())
	else:
		buffer.set_text("")

def start():
	footer.add_page("Lyrics", page)
	libsaria.event.invite("POSTLOAD", set_lyrics, True)

def stop():
	footer.remove_page("Lyrics")

def check_version():
	if libsaria.__major__ != 4:
		return False
	if libsaria.__minor__ == 4:
		return True
	return False
