#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#  
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


##############BIBLIOTECAS A IMPORTAR E DEFINICOES####################

import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmc,xbmcaddon,HTMLParser
from BeautifulSoup import BeautifulSoup
from tools import *
h = HTMLParser.HTMLParser()


versao = '0.0.7'
addon_id = 'plugin.video.smartflix'
selfAddon = xbmcaddon.Addon(id=addon_id)
addonfolder = selfAddon.getAddonInfo('path')
artfolder = addonfolder + '/resources/img/'
fanart = addonfolder + '/fanart.jpg'


################################################## 

#MENUS############################################


def CATEGORIES():
	dialog = xbmcgui.Dialog()
	dialog.ok("Fórum", "Amigos, novo endereço do fórum: forum.freetvbrasil.com, em breve muitas novidades.")
	addDir('Categorias','-',1,artfolder + '2CATEGORIAS.jpg')
	addDir('Últimos Adicionados','http://smartflixfilmeshd.blogspot.com/',2,artfolder + '2TIMOS ADICIONADOS.jpg')
	#addDir('SERIES','http://ecfilmes.com/category/series/',2,artfolder + 'se.jpg')
	addDir('Pesquisar','-',3,artfolder + '2PESQUISA.jpg')
	xbmcplugin.setContent(int(sys.argv[1]), 'movies')
	xbmc.executebuiltin('Container.SetViewMode(500)')
	

###################################################################################
#FUNCOES
def categorias():
	addDir('2013','http://smartflixfilmeshd.blogspot.com/search/label/2013',2,artfolder + '13.jpg')
	addDir('2014','http://smartflixfilmeshd.blogspot.com/search/label/2014',2,artfolder + '14.jpg')
	addDir('Arrow','http://smartflixfilmeshd.blogspot.com/search/label/ARROW',2,artfolder + 'arrow.jpg')
	addDir('Ação','http://smartflixfilmeshd.blogspot.com/search/label/A%C3%87%C3%83O',2,artfolder + 'ac.jpg')
	addDir('Animação','http://smartflixfilmeshd.blogspot.com/search/label/ANIMA%C3%87%C3%83O',2,artfolder + '1.jpg')
	addDir('Aventura','http://smartflixfilmeshd.blogspot.com/search/label/AVENTURA',2,artfolder + 'aventura.jpg')
	addDir('Comedia','http://smartflixfilmeshd.blogspot.com/search/label/COM%C3%89DIA',2,artfolder + 'comedia.jpg')
	addDir('Comedia Romantica','http://smartflixfilmeshd.blogspot.com/search/label/COM%C3%89DIA%20ROM%C3%82NTICA',2,artfolder + 'comediaro.jpg')
	addDir('Crime','http://smartflixfilmeshd.blogspot.com/search/label/CRIME',2,artfolder + 'doc.jpg')
	addDir('Documentários','http://smartflixfilmeshd.blogspot.com/search/label/DOCUMENT%C3%81RIO',2,artfolder + 'doc.jpg')
	addDir('Drama','http://smartflixfilmeshd.blogspot.com/search/label/DRAMA',2,artfolder + 'drama.jpg')
	#addDir('Épico','http://ecfilmes.com/category/epico/',2,artfolder + 'ep.jpg')
	addDir('Fantasia','http://smartflixfilmeshd.blogspot.com/search/label/FANTASIA',2,artfolder + 'fan.jpg')
	addDir('Faroeste','http://smartflixfilmeshd.blogspot.com/search/label/FAROESTE',2,artfolder + 'faroeste.jpg')
	addDir('Ficção','http://smartflixfilmeshd.blogspot.com/search/label/FIC%C3%87%C3%83O%20CIENT%C3%8DFICA',2,artfolder + 'ficcao.jpg')
	addDir('Gospel','http://smartflixfilmeshd.blogspot.com/search/label/GOSPEL',2,artfolder + 'gospel.jpg')
	addDir('Guerra','http://smartflixfilmeshd.blogspot.com/search/label/GUERRA',2,artfolder + 'guerra.jpg')
	addDir('Lutas','http://smartflixfilmeshd.blogspot.com/search/label/LUTAS',2,artfolder + 'lutas.jpg')
	addDir('Manga','http://smartflixfilmeshd.blogspot.com/search/label/MANG%C3%81',2,artfolder + 'man.jpg')
	addDir('Musical','http://smartflixfilmeshd.blogspot.com/search/label/MUSICAL',2,artfolder + 'musical.jpg')
	addDir('Nacional','http://smartflixfilmeshd.blogspot.com/search/label/NACIONAL',2,artfolder + 'nacional.jpg')
	addDir('Policial','http://smartflixfilmeshd.blogspot.com/search/label/POLICIAL',2,artfolder + 'policial.jpg')
	addDir('Romance','http://smartflixfilmeshd.blogspot.com/search/label/ROMANCE',2,artfolder + 'romance.jpg')
	addDir('Suspense','http://smartflixfilmeshd.blogspot.com/search/label/SUSPENSE',2,artfolder + 'suspense.jpg')
	addDir('Series','http://smartflixfilmeshd.blogspot.com/search/label/S%C3%89RIE',2,artfolder + 'series.jpg')
	addDir('Terror','http://smartflixfilmeshd.blogspot.com/search/label/TERROR',2,artfolder + 'terror.jpg')
	addDir('Walking Dead','http://smartflixfilmeshd.blogspot.com/search/label/THE%20WALKING%20DEAD',2,artfolder + '5.jpg')
        addDir('Thriler','http://smartflixfilmeshd.blogspot.com/search/label/THRILLER',2,artfolder + '6.jpg')
        addDir('Epico','http://smartflixfilmeshd.blogspot.com/search/label/%C3%89PICO',2,artfolder + '7.jpg')


def listar_videos(url):
	codigo_fonte = abrir_url(url)
	soup = BeautifulSoup(abrir_url(url))
	#ow = open('C:\\Python27\\smartflix.html','w')
	#ow.write(codigo_fonte)
	#ow.close()
	lista_filmes = BeautifulSoup(soup.find("div", { "class" : "widget Blog" }).prettify())
	filmes = lista_filmes.findAll("div", { "class" : "post hentry" })
	a=[]
	for filme in filmes:
		print 'Divs: \n' + str(filme('div'))
		plot = ''
		for div in filme('div'):
			if 'Sinopse' in div.text:
				plot = div.text
				break
		if not plot:
			plot = filme('span')[1].text
		temp = [filme('div')[0].a["href"],html_replace_clean(filme('div')[0].a.text.encode('ascii', 'xmlcharrefreplace')),filme('img')[0]["src"],html_replace_clean(plot.encode('ascii', 'xmlcharrefreplace'))] 
		a.append(temp)
	#	
	total = len(a)
	for url2, titulo, img, plot in a:
		titulo = titulo.replace('&#8211;',"-").replace('&#8217;',"'")	
		addDir(titulo,url2,4,img,True,total,plot)
		
		
	#page = re.compile("<link rel='next' href='(.+?)' />").findall(codigo_fonte)
	#for prox_pagina in page:
	p_page = soup.find('a',{'class':'blog-pager-older-link'})
	if p_page:
		addDir('Página Seguinte >>',p_page['href'],2,artfolder + 'prox.jpg')
	
	xbmcplugin.setContent(int(sys.argv[1]), 'movies')
	xbmc.executebuiltin('Container.SetViewMode(503)')
	
def obtem_url_google(url):

	html = abrir_url(url)
	#ow = open('C:\\Python27\\gdrive.html','w')
	#ow.write(html)
	#ow.close()
	arquivo = re.findall('<meta itemprop="name" content="(.*?)">', html)[0]
	FLASHVARS_START = 'flashVars":{'
	start = html.find(FLASHVARS_START) + len(FLASHVARS_START)
	end = html.find('}', start)
	
	flashvars = html[start:end]
	
	d = flashvars.decode('unicode-escape')
	decoded = urllib2.unquote(urllib2.unquote(d))
	#print "ORG Decoded: " + decoded
	
	urls = [l for l in decoded.split('url=') if 'mp4' in l and l.startswith('https')]
	ttsurls = decoded[decoded.find('"ttsurl":"') + len('"ttsurl":"'): decoded.find('",', decoded.find('"ttsurl":"'))] + '&kind&lang=pt-BR&name&type=track'
	ttsurls_id = ttsurls[ttsurls.find('timedtext?id=') + len('timedtext?id='): ttsurls.find('&', ttsurls.find('timedtext?id='))]
	#print "ORG Urls: " + str(urls)
	#print "ORG Ttsurls_id: " + str(ttsurls_id)
	#print "ORG Ttsurls: " + str(ttsurls) + '&v=' + str(ttsurls_id)
	qualidade = []
	url_video = []
	for u in urls:
		itags = {5:'Baixa Qualidade, 240p, FLV, 400x240',
			 17:'Baixa Qualidade, 144p, 3GP, 0x0',
			 18:'Media Qualidade, 480p, MP4, 480x360',
			 59:'Media Qualidade, 360p, MP4, 480x360',
			 22:'Alta Qualidade, 720p, MP4, 1280x720',
			 34:'Media Qualidade, 360p, FLV, 640x360',
			 35:'Standard Definition, 480p, FLV, 854x480',
			 36:'Baixa Qualidade, 240p, 3GP, 0x0',
			 37:'Alta Qualidade, 1080p, MP4, 1920x1080',
			 38:'Original Definition, MP4, 4096x3072',
			 43:'Media Qualidade, 360p, WebM, 640x360',
			 44:'Standard Definition, 480p, WebM, 854x480',
			 45:'Alta Qualidade, 720p, WebM, 1280x720',
			 46:'Alta Qualidade, 1080p, WebM, 1280x720',
			 82:'Media Qualidade 3D, 360p, MP4, 640x360',
			 84:'Alta Qualidade 3D, 720p, MP4, 1280x720',
			 100:'Media Qualidade 3D, 360p, WebM, 640x360',
			 102:'Alta Qualidade 3D, 720p, WebM, 1280x720'}
		q = 'quality='
		i = 'itag='
		quality = u[u.find(q) + len(q): u.find(',', u.find(q))]
		itag = u[u.find(i) + len(i): u.find('&', u.find(i))]
		#print "ORG qualitys: " + quality
		#print "ORG itag: " + itag
		try:
			quality = itags[int(itag)]
		except:
			pass
		qualidade.append(quality)
		url_video.append(u[:-1])
	index = xbmcgui.Dialog().select('Qualidade do vídeo:', qualidade)
	if index == -1: return['-','-'] # Tive que alterar esta linha para corrigir um pequeno erro
	return [url_video[index],str(ttsurls) + '&v=' + str(ttsurls_id), arquivo]

def obtem_url_dropvideo(url):
	codigo_fonte = abrir_url(url)
	try:
		if not 'dropvideo.com/embed/' in url:
			id_video = re.findall(r'<iframe src="http://www.dropvideo.com/embed/(.*?)/"',codigo_fonte)[0]
			codigo_fonte = abrir_url('http://www.dropvideo.com/embed/%s/' % id_video)
			url_video = re.findall(r'var vurl2 = "(.*?)";',codigo_fonte)[0]
			url_legendas =	re.compile('var vsubtitle = "(.*?)";').findall(codigo_fonte)[0]
		else:
			codigo_fonte = abrir_url(url)
			url_video = re.findall(r'var vurl2 = "(.*?)";',codigo_fonte)[0]
			url_legendas =	re.compile('var vsubtitle = "(.*?)";').findall(codigo_fonte)[0]
	except:
		url_video = '-'
		url_legendas = '-'
	return [url_video,url_legendas]

def obtem_url_vk(url):
	print url.replace('amp;','')
	codigo_fonte = abrir_url(url.replace('amp;',''))
	qualidade = []
	urls = []
	try:
		urls_video = re.findall(r'url([0-9]+)=(.*?)&', codigo_fonte)
		for qualidade_ , url_ in urls_video:
			qualidade_ = qualidade_+"p"
			if not qualidade_ in qualidade:
				qualidade.append(qualidade_)
			if not url_ in urls:
				urls.append(url_)
		index = xbmcgui.Dialog().select('Qualidade do vídeo:', qualidade)
		return [urls[index],"-"]
	except:
		return ["-","-"]
def obtem_url_vodlocker(url):
	codigo_fonte = abrir_url(url)
	
	try:
		url_video = re.findall(r'file:."(.*?)"',codigo_fonte)[0]
		return [url_video,"-"]
	except:
		return ["-","-"]

def obtem_url_firedrive(url):
	import mechanize, cookielib
	
	br = mechanize.Browser()

	cj = cookielib.LWPCookieJar()
	br.set_cookiejar(cj)
	
	br.set_handle_equiv(True)
	br.set_handle_gzip(True)
	br.set_handle_redirect(True)
	br.set_handle_referer(True)
	br.set_handle_robots(False)
	
	br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
	
	br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'),("Referer","http://www.firedrive.com")]
	br.open(url)
	br.select_form(nr=0)
	response1 = br.submit()
	html = response1.read()
	
	video_url = re.findall(r"file:.'(.*?)',",html)[0]
	return [video_url,"-"]

def obtem_url_picasa(url):
	itags = {5:'Baixa Qualidade, 240p, FLV, 400x240',
		17:'Baixa Qualidade, 144p, 3GP, 0x0',
		18:'Media Qualidade, 480p, MP4, 480x360',
		59:'Media Qualidade, 360p, MP4, 480x360',
		22:'Alta Qualidade, 720p, MP4, 1280x720',
		34:'Media Qualidade, 360p, FLV, 640x360',
		35:'Standard Definition, 480p, FLV, 854x480',
		36:'Baixa Qualidade, 240p, 3GP, 0x0',
		37:'Alta Qualidade, 1080p, MP4, 1920x1080',
		38:'Original Definition, MP4, 4096x3072',
		43:'Media Qualidade, 360p, WebM, 640x360',
		44:'Standard Definition, 480p, WebM, 854x480',
		45:'Alta Qualidade, 720p, WebM, 1280x720',
		46:'Alta Qualidade, 1080p, WebM, 1280x720',
		82:'Media Qualidade 3D, 360p, MP4, 640x360',
		84:'Alta Qualidade 3D, 720p, MP4, 1280x720',
		100:'Media Qualidade 3D, 360p, WebM, 640x360',
		102:'Alta Qualidade 3D, 720p, WebM, 1280x720'}
	codigo_fonte_player = abrir_url(url)
	#try:
	itags_ = []
	id_video = re.findall(r'FlashVars="plugins=plugins1/proxy.swf&proxy.link=https://picasaweb.google.com/lh/photo/(.*?)&skin=newtubedark.zip&proxy.reloader=false"',codigo_fonte_player)[0]
	itag37 = "http://redirector.googlevideo.com/videoplayback?id=" + id_video + "&itag=37&source=picasa&cmo=sensitive_content=yes&ip=0.0.0.0&ipbits=0&expire=1397243357&sparams=id%2Citag%2Csource%2Cip%2Cipbits%2Cexpire&signature=CA66CBBEF3510DDF0054366A11222FABBD77B0F6.56EF5482EFC67CB051B0A5F67AFFF28A599C92E4&key=lh1"
	url_video_picasa = 'https://picasaweb.google.com/lh/photo/%s' % id_video
	redirectors = re.findall(r'"(http://redirector.googlevideo.com/videoplayback.*?)"',abrir_url(url_video_picasa))
	for redirector in redirectors:
		itag = re.findall(r'&itag=([0-9]+?)&',redirector)[0]
		itag = itags[int(itag)]
		itags_.append(itag)
		
	#redirect = urllib2.unquote(re.findall(r"!'(.*?)'",abrir_url(url_video_picasa))[0])
	index = xbmcgui.Dialog().select('Qualidade do vídeo:', itags_)
	return [redirectors[index],"-"]
	#except:
	#	return ["-","-"]

def player(name,url,iconimage):
	google = r'src="(.*?google.*?/preview)"'
	picasa = r'src="(.*?filmesonlinebr.*?/player/.*?)"'
	vk = r'src="(.*?vk.*?/video.*?)"'
	nvideo = r'src="(.*?nowvideo.*?/embed.*?)"'
	dropvideo = r'src="(.*?dropvideo.*?/embed.*?)"'
	vodlocker = r'src="(.*?vodlocker.*?/embed.*?)"'
	dropmega = r'src=".*?dropmega.*?id=(.*?)"'
	
	mensagemprogresso = xbmcgui.DialogProgress()
	mensagemprogresso.create('EcFilmes', 'A resolver link','Por favor aguarde...')
	mensagemprogresso.update(33)
	
	links = []
	hosts = []
	matriz = []
	codigo_fonte = abrir_url(url)
	
	try:
		links.append(re.findall(picasa, codigo_fonte)[0])
		hosts.append('Picasa')
	except:
		pass
	
	try:
		links.append(re.findall(google, codigo_fonte)[0])
		hosts.append('Gdrive')
	except:
		pass
	
	try:
		links.append(re.findall(vk, codigo_fonte)[0])
		hosts.append('Vk')
	except:
		pass
	
	try:
		links.append(re.findall(nvideo, codigo_fonte)[0])
		hosts.append('Nowvideo - Sem suporte')
	except:
		pass
	
	try:
		links.append(re.findall(dropvideo, codigo_fonte)[0])
		hosts.append('Dropvideo')
	except:
		pass
	
	try:
		links.append('http://www.dropvideo.com/embed/'+re.findall(dropmega, codigo_fonte)[0])
		hosts.append('Dropvideo')
	except:
		pass
	
	try:
		links.append(re.findall(vodlocker, codigo_fonte)[0])
		hosts.append('Vodlocker - Sem suporte')
	except:
		pass
	
	if not hosts:
		return
	
	index = xbmcgui.Dialog().select('Selecione um dos hosts suportados :', hosts)
	
	if index == -1:
		return

	url_video = links[index]
	mensagemprogresso.update(66)
	
	print 'Player url: %s' % url_video
	if 'google' in url_video:
		matriz = obtem_url_google(url_video)
	elif 'dropvideo.com/embed' in url_video:
		matriz = obtem_url_dropvideo(url_video)   # esta linha está a mais
	elif 'filmesonlinebr.info/player' in url_video:
		matriz = obtem_url_picasa(url_video)
	elif 'vk.com/video_ext' in url_video:
		matriz = obtem_url_vk(url_video)
	else:
		print "Falha: " + str(url_video)
	print matriz
	url = matriz[0]
	print url
	if url=='-': return
	legendas = matriz[1]
	print "Url do gdrive: " + str(url_video)
	print "Legendas: " + str(legendas)
	try:
		if matriz[2]:
			name = matriz[2]
	except:
		pass
	mensagemprogresso.update(100)
	mensagemprogresso.close()
	
	#listitem = xbmcgui.ListItem() # name, iconImage="DefaultVideo.png", thumbnailImage="DefaultVideo.png"
	#listitem.setPath(url)
	#listitem.setProperty('mimetype','video/mp4')
	#listitem.setProperty('IsPlayable', 'true')
	##try:
	#xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	#xbmcPlayer.play(url,listitem)
	listitem = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage, path=name)
	listitem.setThumbnailImage(iconimage)
	listitem.setProperty('mimetype','video/mp4')
	listitem.setInfo('video', {'Title': name, 'Originaltitle':name})
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=str(url),listitem=listitem)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
	#xbmc.Player( xbmc.PLAYER_CORE_MPLAYER ).play(url, listitem)
	#if legendas != '-':
	#	if 'timedtext' in legendas:
	#		#legenda = xmltosrt.convert(legendas)
	#		#try:
	#			import os.path
	#			sfile = os.path.join(xbmc.translatePath("special://temp"),'sub.srt')
	#			sfile_xml = os.path.join(xbmc.translatePath("special://temp"),'sub.xml')#timedtext
	#			sub_file_xml = open(sfile_xml,'w')
	#			sub_file_xml.write(urllib2.urlopen(legendas).read())
	#			sub_file_xml.close()
	#			print "Sfile.srt : " + sfile_xml
	#			xmltosrt.main(sfile_xml)
	#			xbmcPlayer.setSubtitles(sfile)
	#		#except:
	#		#	pass
	#	else:
	#		xbmcPlayer.setSubtitles(legendas)
	
def pesquisa():
	keyb = xbmc.Keyboard('', 'faca a procura') #Chama o keyboard do XBMC com a frase indicada
	keyb.doModal() #Espera ate que seja confirmada uma determinada string
	if (keyb.isConfirmed()): #Se a entrada estiver confirmada (isto e, se carregar no OK)
		search = keyb.getText() #Variavel search fica definida com o conteudo do formulario
		parametro_pesquisa=urllib.quote(search) #parametro_pesquisa faz o quote da expressao search, isto Ã©, escapa os parametros necessarios para ser incorporado num endereÃ§o url
		url = 'http://smartflixfilmeshd.blogspot.com.br/search?q=%s&submit=Busca' % str(parametro_pesquisa) #nova definicao de url. str forÃ§a o parametro de pesquisa a ser uma string
		listar_videos(url) #chama a funÃ§Ã£o listar_videos com o url definido em cima

		###################################################################################

'''def addDirPlayer(name,url,mode,iconimage,total):
	# plot é a sinopse do filme... da maneira que está definido não apanha sinopses. (nota: não sei se o site tem sinopses. Se não tiver, este codigo é desnecessario)
	# Isto estava lento porque esta função estava a pesquisar por sinopses mas nunca encontrava
	codigo_fonte = abrir_url(url)
	try: plot = re.compile('<meta name="description" content="(.+?)" />').findall(codigo_fonte)[0]
	except: plot = 'Erro a obter sinopse...'
	
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="Video", infoLabels= { "Title": name,
											 "OriginalTitle": name,
											 "Plot": plot 
											 } )
	cm = []
	cm.append(('Sinopse', 'XBMC.Action(Info)'))
	liz.addContextMenuItems(cm, replaceItems=True)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False,totalItems = total)
	return ok'''

def abrir_url(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link

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

#def addDir(name,url,mode,iconimage,pasta=True,total=1):
#	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
#	ok=True
#	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
#	liz.setProperty('fanart_image', fanart)
#	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=total)
#	return ok

def addDir(name,url,mode,iconimage,pasta=True,total=1,plot=''):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="video", infoLabels={ "title": name, "plot": plot } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=total)
	return ok

############################################################################################################
#                                               GET PARAMS                                                 #
############################################################################################################
              
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

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


try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

try:        
        iconimage=urllib.unquote_plus(params["iconimage"])
except:
        pass


print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Iconimage: "+str(iconimage)




###############################################################################################################
#                                                   MODOS                                                     #
###############################################################################################################


if mode==None or url==None or len(url)<1:
        print ""
        CATEGORIES()

elif mode==1:
	print ""
	categorias()
	
elif mode==2:
	print ""
	listar_videos(url)
	
elif mode==3:
	print ""
	pesquisa()

elif mode==4:
	print ""
	print iconimage
	player(name,url,iconimage)
	
elif mode==5:
	print ""
	listar_videos_M18(url)
	
xbmcplugin.endOfDirectory(int(sys.argv[1]))