# -*- coding: utf-8 -*-
import xbmc, xbmcplugin, xbmcaddon
import sys, re, json, math, time, urllib, urllib2, urlparse, cookielib, datetime
import resources.lib.common as common

handle = int(sys.argv[1])
AddonID = 'plugin.video.idanplus'
Addon = xbmcaddon.Addon(AddonID)
sortBy = int(Addon.getSetting("tenSortBy"))
module = 'ten'
baseUrl = 'http://10tv.nana10.co.il'
seriesConvUrl = 'https://raw.githubusercontent.com/Fishenzon/repo/master/seriesconv.json'
userAgent = common.GetUserAgent()

def GetCategoriesList(iconimage):
	sortString = common.GetLocaleString(30002) if sortBy == 0 else common.GetLocaleString(30003)
	name = "{0}: {1}".format(common.GetLocaleString(30001), sortString)
	common.addDir(name, "toggleSortingMethod", 7, iconimage, {"Title": name, "Plot": "{0}[CR]{1}[CR]{2} / {3}".format(name, common.GetLocaleString(30004), common.GetLocaleString(30002), common.GetLocaleString(30003))}, module=module, isFolder=False)
	url = baseUrl
	text = common.OpenURL(url)
	names = re.compile('t1677_leshonit.+?onclick=".+?\((.+?)\).+?>(.+?)<').findall(text)
	for id, name in names:
		common.addDir(name, id, 1, iconimage, infos={"Title": name}, module=module)

def GetSeriesList(id, name):
	try:
		text = common.OpenURL(seriesConvUrl)
		seriesConv = json.loads(text)
	except:
		seriesConv = {}
	url = baseUrl
	text = common.OpenURL(url)
	matches = re.compile('t1677_tab{0}.+?t1677_programs overview(.+?)</div>\s+</div>\s+</div>'.format(id), re.S).findall(text)
	matches = re.compile('<div class="t1677_Menu" onclick=".+?\'(.+?)\'.+?img src="(.+?)"', re.S).findall(matches[0])
	for url, iconimage in matches:
		if not url.startswith('http'):
			continue
		name = seriesConv.get(url, '').encode('utf-8')
		if name == '':
			xbmc.log('--{0}--'.format(url), 5)
		name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), name)
		common.addDir(name, url.replace('&amp;','&'), 2, 'http:{0}'.format(iconimage), infos={"Title": name}, module=module)

def GetSectionsList(url, iconimage):
	base = '{0}://{1}'.format(urlparse.urlparse(url).scheme, urlparse.urlparse(url).netloc)
	#if base != baseUrl:
	#	xbmc.log(str(base), 5)
	#	xbmc.log(str(baseUrl), 5)
	#	req = urllib2.Request(url)
	#	response = urllib2.urlopen(req)
	#	url = response.url
	text = common.OpenURL(url)
	prms = urlparse.parse_qs(urlparse.urlparse(url).query.lower())
	if 'sectionid' in url.lower():
		GetEpisodesList('{0}/Video/?CategoryID={1}&TypeID=13&pid=48&SectionID={1}&VideoID={{0}}&PageNumber=1'.format(baseUrl, prms['sectionid'][0]), iconimage)
		return
	matches = re.compile('<meta property="og:url" content="(.*?)" />').findall(text)
	if matches[0].strip() == '':
		matches = re.compile('<div class="middle">(.+?)<div class="left-list">', re.S).findall(text)
		GetEpisodesList2(matches[0], base)
		return
	categoryID = matches[0] if 'http' not in matches[0] else matches[0][matches[0].find('?CategoryID=')+12:]
	baseVid = '{0}/Video/?CategoryID={1}&TypeID=13&pid=48'.format(baseUrl, categoryID)
	matches = re.compile('"t1672_tabs(.+?)</div>', re.S).findall(text)
	if len(matches) > 0:
		matches = re.compile('sectionid="(.+?)\s*?".+?>(.+?)<', re.S).findall(matches[0])
	else:
		matches = re.compile('FloatingMenuItemsContainer(.+?)<span class="LastLink">').findall(text)
		if len(matches) > 0:
			matches = re.compile('href.+?SectionID=(.+?)".*?>(.+?)</a>').findall(matches[0])
		else:
			return
	for id, name in matches:
		name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("timesColor"), name)
		common.addDir(name, '{0}&SectionID={1}&VideoID={{0}}&PageNumber=1'.format(baseVid, id), 3, iconimage, infos={"Title": name}, module=module)

def GetEpisodesList(url, iconimage):
	episodes = int(Addon.getSetting("tenEpisodes"))
	prms = urlparse.parse_qs(urlparse.urlparse(url).query)
	text = common.OpenURL('http://common.nana10.co.il/SectionVOD/GetSectionVOD.ashx?PageSize={0}&FetchVideo=1&PageNumber={1}&SectionID={2}'.format(episodes, prms['PageNumber'][0], prms['SectionID'][0]))
	url = url[:url.find('&PageNumber=')]
	a = json.loads(text[1:-1])
	pages = int(math.ceil(a["TotalResults"] * 1.0 / episodes))
	for i in range(episodes):
		if episodes * (a["PageNumber"] - 1) + i < a["TotalResults"]:
			b = a["HeadlineList"][i]
			name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("chColor"), b["Title"].encode("utf-8"))
			imageID = b["MediaStockImageID"]
			basePic = 'http://f.nanafiles.co.il/upload' if len(str(imageID)) > 5 else 'http://source.nanafiles.co.il/Upload3'
			aired = re.compile('/Date\((.*)\)/').findall(b.get("ModifyDateActual", ''))[0]
			if aired != '':
				try:
					aired = time.strftime('%d/%m/%Y', time.localtime(int(aired) / 1000))
				except:
					pass
			_url = url.format(b["VideoID"])
			_icon = '{0}/mediastock/img/693/0/{1}/{2}.jpg'.format(basePic, str(imageID)[:-3], imageID)
			common.addDir(name, _url, 4, _icon, infos={"Title": name, "Plot": b["SubTitle"], "Aired": aired}, contextMenu=[(common.GetLocaleString(30005), 'RunPlugin({0}?url={1}&name={2}&mode=4&iconimage={3}&moredata=choose&module=ten)'.format(sys.argv[0], urllib.quote_plus(_url), name, urllib.quote_plus(_icon)))], moreData='best', module=module, isFolder=False, isPlayable=True)
		else:
			break
	
	if a["PageNumber"] > 1:
		name = "[COLOR green] <<  {0}[/COLOR]".format(common.GetLocaleString(30011))
		common.addDir(name, '{0}&PageNumber={1}'.format(url, a["PageNumber"] - 1), 3, iconimage, infos={"Title": name, "Plot": name}, module=module)
	if pages > a["PageNumber"]:
		name = "[COLOR green] >>  {0}[/COLOR]".format(common.GetLocaleString(30012))
		common.addDir(name, '{0}&PageNumber={1}'.format(url, a["PageNumber"] + 1), 3, iconimage, infos={"Title": name, "Plot": name}, module=module)
	if pages > 1:
		name = "[COLOR green] ><  {0}[/COLOR]".format(common.GetLocaleString(30013))
		common.addDir(name, '{0}&PageNumber={1}&Pages={2}'.format(url, a["PageNumber"], pages), 5, iconimage, infos={"Title": name, "Plot": name}, module=module)

def GetEpisodesList2(text, base):
	matches = re.compile('<div.+?<a href="(.+?)".*?<div class="sixteen_nine">\s*?<img.*?alt="(.+?)".*?data-src="(.+?)" />.*?<div class="content-title">(.*?)<div.*?data-time="(\d*)"></span>', re.S).findall(text)
	for url, name, image, plot, published in matches:
		aired = datetime.datetime.fromtimestamp(int(published)).strftime('%d/%m/%Y')
		if 'http' not in url:
			url = base + url
		name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("chColor"), common.UnEscapeXML(name.strip()))
		common.addDir(name, url, 4, image, infos={"Title": name, "Plot": common.UnEscapeXML(plot.strip()), "Aired": aired}, contextMenu=[(common.GetLocaleString(30005), 'RunPlugin({0}?url={1}&name={2}&mode=4&iconimage={3}&moredata=choose&module=ten)'.format(sys.argv[0], urllib.quote_plus(url), name, urllib.quote_plus(image)))], moreData='best', module=module, isFolder=False, isPlayable=True)

def Play(url, name='', iconimage='', quality='best'):
	common.DelCookies()
	headers={"User-Agent": userAgent}
	text = common.OpenURL(url, headers=headers)
	matches = re.compile('UserID=(.+?);GroupId=(.+?);').findall(text)
	if len(matches) < 1:
		matches = re.compile('userid=(.+?)&groupid=(.+?)&').findall(text)
	url = 'http://vod.ch10.cloudvideoplatform.com/api/getlink/GetFlash?showID={0}&userID={1}'.format(matches[0][1], matches[0][0])
	text = common.OpenURL(url, headers=headers)
	result = json.loads(text)[0]
	mf = result['MediaFile'].split('.')
	base_url =  '{0}{1}{2}{3}{4}.{5}'.format(result['ProtocolType'], result['ServerAddress'], result['MediaRoot'], mf[0], result['Bitrates'], mf[1])
	url = '{0}{1}{2}'.format(base_url, result['StreamingType'], result['Params'].replace('&amp;', '&'))
	cookie_jar = cookielib.LWPCookieJar()
	link = common.GetStreams(url, headers=headers, CookieJar=cookie_jar, quality=quality)
	cookies = "&".join(['Cookie={0}'.format(urllib.quote('{0}={1}'.format(_cookie.name, _cookie.value))) for _cookie in cookie_jar])
	final = '{0}|User-Agent={1}'.format(link, userAgent)
	if cookies != '':
		final = '{0}&{1}'.format(final, cookies)
	common.PlayStream(final, quality, name, iconimage)

def WatchLive(name='', iconimage='', quality='best'):
	headers={"User-Agent": userAgent}
	text = common.OpenURL('http://live.ch10.cloudvideoplatform.com/api/getlink/?servertype=hls&ch=1', headers=headers)
	link = common.GetStreams(json.loads(text)[0]['Link'], headers=headers, quality=quality)
	final = '{0}|User-Agent={1}'.format(link, userAgent)
	common.PlayStream(final, quality, name, iconimage)

def Run(name, url, mode, iconimage='', moreData=''):
	if mode == 0:
		# "----------- Categories: ---------------"
		GetCategoriesList(iconimage)
	elif mode == 1:
		# "------------- Series: -----------------"
		GetSeriesList(url, name)
	elif mode == 2:
		# "------------ Sections: ----------------"
		GetSectionsList(url, iconimage)
	elif mode == 3:
		# "------------ Episodes: ----------------"
		GetEpisodesList(url, iconimage)
	elif mode == 4:
		# "-------- Playing episode  -------------"
		Play(url, name, iconimage, moreData)
	elif mode == 5:
		# "- Move to a specific episodes' page  --"
		prms = urlparse.parse_qs(urlparse.urlparse(url).query)
		index = common.GetIndexFromUser(name, int(prms['Pages'][0]))
		GetEpisodesList('{0}&PageNumber={1}'.format(url[:url.find('&PageNumber=')], index), iconimage)
	elif mode == 6:
		WatchLive(name, iconimage, moreData)
	elif mode == 7:	#------------- Toggle Lists' sorting method: -----------------
		common.ToggleSortMethod('tenSortBy', sortBy)
		
	if mode == 1:
		common.SetViewMode('videos')
	elif mode != 0:
		common.SetViewMode('episodes')
	if sortBy == 1 and mode == 1:
		xbmcplugin.addSortMethod(handle, 1)
