PluginInterface.require_command("ogginfo")
from mx import DateTime

class OggVorbisFile(PluginInterface.File):

	date = None
	sample_rate = None
	track_number = None
	bitrate = None
	title = None
	album = None
	genre = None
	artist = None
	# fixme implement comment and length extraction
# 	comment = None
# 	length = None

	OggVorbisFile_catalogable = [
		"date","sample_rate","track_number","bitrate",
		"title","album","genre","artist","comment","length" ]

	def __init__(self,filename,mimetype,volume):
		PluginInterface.File.__init__(self,filename,mimetype,volume)
		metadata = ogginfo_extract(filename)
		for key,value in metadata.iteritems():
			if key == "date":
				self.date = DateTime.DateTime(value,1,1)
			elif key == "Rate":
				self.sample_rate = value
			elif key == "tracknumber":
				self.track_number = value
			elif key == "title":
				self.title = value
			elif key == "album":
				self.album = value
			elif key == "Average bitrate":
				self.bitrate = value
			elif key == "genre":
				self.genre = value
# 			elif key == "id3.comment" and len(value) > 0:
# 				self.comment = value
# 			elif key == "technical.length":
# 				self.length = value
			elif key == "artist":
				self.artist = value

	def __repr__(self):
		return "Ogg Vorbis music file %s (%s - %s - %s)"%(self.get_filename(),self.artist,self.album,self.title)

def get_factory():
	return OggVorbisFile

def get_mimetypes():
	return ["audio/vorbis","application/ogg"]


def ogginfo_extract(filename):
	import commands
	output = commands.getoutput("LANG=en_US.UTF-8 ogginfo %s"%PluginInterface.shell_quote(filename))
	output = PluginInterface.transcode_to_platform_encoding(output,"UTF-8")
	lines = output.splitlines()
	lines = [ a.strip() for a in lines ]
	tags = [ a.split("=",1) for a in lines if a.find("=") != -1 ]
	techinfo = [ a.split(":",1) for a in lines if a.find(":") != -1 ]
	t = {}
	for tag in tags:
		key,value = tag[0],tag[1]
		key = key.strip()
		value = value.strip()
		t[key] = value
	for techin in techinfo:
		key,value = techin[0],techin[1]
		key = key.strip()
		value = value.strip()
		t[key] = value
	
	key = "date"
	if t.has_key(key):
		try: t[key] = int(t[key])
		except:
			PluginInterface.log("vorbis-tools-audio-vorbis").warning("Error decoding year (%s)",t[key],exc_info=True)
			del(t[key])
	key = "tracknumber"
	if t.has_key(key):
		try: t[key] = int(t[key])
		except:
			PluginInterface.log("vorbis-tools-audio-vorbis").warning("Error decoding track (%s)",t[key],exc_info=True)
			del(t[key])
# 	key = "COMM"
# 	if t.has_key(key):
# 		if t[key].startswith("(ID3v1 Comment)["): t[key] = t[key][22:]
	key = "Average bitrate"
	if t.has_key(key):
		try: t[key] = float(t[key].split(" ")[0])*1000
		except: 
			PluginInterface.log("vorbis-tools-audio-vorbis").warning("Error decoding bitrate (%s)",t[key],exc_info=True)
			del(t[key])
	key = "Rate"
	if t.has_key(key):
		try:
			t[key] = int(t[key])
		except: 
			PluginInterface.log("vorbis-tools-audio-vorbis").warning("Error decoding frequency (%s)",t[key],exc_info=True)
			del(t[key])
	
	return t
