# XBMC Plugin for listing and playing Zeipis TV recordings
# (c) 2009 Ben Bucksch

import urllib, urllib2, xbmcplugin, xbmcgui, sys
from xml.dom.minidom import parseString

def start():
	listURL = baseURL + "/recorded/list/?sortBy=orderrecorded&sortDir=desc&filter=showtype-eq-"
	addDir(xbmc.getLocalizedString(30100), "", "list-videos", listURL + "movie");
	addDir(xbmc.getLocalizedString(30101), "", "list-titles", listURL + "series&onlyOnePer=title");

def listVideos(url):
	videos = readVideosFromXML(fetchURL(url))
	for video in videos:
		#addVideo(video.fullTitle, video.previewURL, video.videoURL)
		addVideo(video.fullTitle, "", video.videoURL)
		# TODO for series, only subtitle

def listTitles(url):
	videos = readVideosFromXML(fetchURL(url))
	# TODO filter by showtype, too
	listURL = baseURL + "/recorded/list/?sortBy=orderrecorded&sortDir=desc&filter=title-eq-"
	for r in videos:
		addDir(r.title, "", "list-videos", listURL + urllib.quote_plus(r.title))



def fetchURL(url):
       	req = urllib2.Request(url)
        conn = urllib2.urlopen(req)
        response = conn.read()
        conn.close()
	return response

def readVideosFromXML(xmlStr):
	result = []
	dom = parseString(xmlStr)
	for x in dom.getElementsByTagName('recording'):
		r = Recording()
		r.readFromXML(x)
		result.append(r)
	return result

class Recording:
	fullTitle = None
	title = None
	subtitle = None
	originalTitle = None
	originalSubtitle = None
	genre = None
	showtype = None
	videoURL = None
	previewURL = None
	seen = None
	keep = None
	
	def readFromXML(self, xe):
		self.title = _getElementContent(xe, "title")
		self.subtitle = _getElementContent(xe, "subtitle")
		self.originalTitle = _getElementContent(xe, "originaltitle")
		self.originalSubtitle = _getElementContent(xe, "originalsubtitle")
		self.genre = _getElementContent(xe, "genre")
		self.showtype = _getElementAttribute(xe, "showtype", "name")
		self.seen = _getElementAttribute(xe, "management", "seen")
		self.videoURL = _getElementAttribute(xe, "location", "url")
		self.previewURL = _getElementAttribute(xe, "preview", "url")

		self.fullTitle = self.title
		if (self.subtitle):
			self.fullTitle += " - " + self.subtitle

		# TODO more attributes, preview types

def _getElementContent(xe, tagname):
	nodes = xe.getElementsByTagName(tagname)
	if len(nodes) > 0:
		return nodes[0].firstChild.nodeValue
	else:
		return None
def _getElementAttribute(xe, tagname, attr):
	nodes = xe.getElementsByTagName(tagname)
	if len(nodes) > 0:
		return nodes[0].getAttribute(attr)
	else:
		return None

	# TODO management



# <copied from="example plugin">
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
        return param

def addVideo(name, iconimage, url):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok

def addDir(name, iconimage, mode, url):
        u=sys.argv[0]+"?mode="+urllib.quote_plus(mode)+"&name="+urllib.quote_plus(name)+"&url="+urllib.quote_plus(url)
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
# </copied>


# Settings
hostname = xbmcplugin.getSetting("hostname")
port = int(xbmcplugin.getSetting("port"))
if hostname == None or len(hostname) < 1:
	xbmcplugin.openSettings(url=sys.argv[0])
baseURL = "http://" + hostname + ":" + str(port)


params=get_params()
mode=None
url=None
name=None

#Note: mode is a string here
try:
        mode=urllib.unquote_plus(params["mode"])
except:
        pass
try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass

print "Mode: " + str(mode)
print "URL:  " + str(url)
print "Name: " + str(name)
print "arg 0 - plugin: " + sys.argv[0]
print "arg 1 - handle: " + sys.argv[1]
print "arg 2 - url: " + sys.argv[2]

if mode == None:
	start()
elif mode == "list-videos":
        listVideos(url)
elif mode == "list-titles":
        listTitles(url)
else:
	start()

xbmcplugin.endOfDirectory(int(sys.argv[1]))
