# -*- coding: utf-8 -*-
import xbmc, xbmcplugin, xbmcaddon
import os, sys, uuid, urllib, re, json, cookielib
from datetime import date
import resources.lib.common as common

handle = int(sys.argv[1])
AddonID = 'plugin.video.idanplus'
Addon = xbmcaddon.Addon(AddonID)
imagesDir = xbmc.translatePath(os.path.join(Addon.getAddonInfo('path'), 'resources', 'images')).decode("utf-8")
module = 'keshet'
AddonName = "Idan Plus"
icon = Addon.getAddonInfo('icon')
sortBy = int(Addon.getSetting("makoSortBy"))
deviceID = Addon.getSetting("makoDeviceID")
if deviceID.strip() == '':
	uuidStr = str(uuid.uuid1()).upper()
	deviceID = "W{0}{1}".format(uuidStr[:8], uuidStr[9:])
	Addon.setSetting("makoDeviceID", deviceID)
username = Addon.getSetting("makoUsername")
password = Addon.getSetting("makoPassword")
baseUrl = 'http://www.mako.co.il'
endings = 'type=service&device=desktop&strto=true'
UA = 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, infos={"Title": name, "Plot": "{0}[CR]{1}[CR]{2} / {3}".format(name, common.GetLocaleString(30004), common.GetLocaleString(30002), common.GetLocaleString(30003))}, module=module, isFolder=False)
	name = "חיפוש"
	common.addDir(name, "{0}/autocomplete/vodAutocompletion.ashx?query={{0}}&max=60&id=query".format(baseUrl), 6, os.path.join(imagesDir, 'search.jpg'), infos={"Title": name, "Plot": "חיפוש"}, module=module)
	name = "תכניות MakoTV"
	common.addDir(name, "{0}/mako-vod-index".format(baseUrl), 1, os.path.join(imagesDir, 'vod.jpg'), infos={"Title": name, "Plot": "צפיה בתכני MakoTV"}, module=module)
	name = "ילדים - חינוכית"
	common.addDir(name, "{0}/mako-vod-special/educational-tv".format(baseUrl), 1, os.path.join(imagesDir, 'kids-programs.jpg'), infos={"Title": name, "Plot": "צפיה בתכניות ילדים"}, module=module)
	name = "תכניות ילדים"
	common.addDir(name, "{0}/mako-vod-kids".format(baseUrl), 1, os.path.join(imagesDir, 'kids-programs.jpg'), infos={"Title": name, "Plot": "צפיה בתכניות ילדים"}, module=module)
	name = "קלטות ילדים"
	common.addDir(name, "{0}/mako-vod-kids".format(baseUrl), 1, os.path.join(imagesDir, 'kids.jpg'), infos={"Title": name, "Plot": "צפיה בקלטות ילדים"}, module=module)
	name = "ילדים - WIZ"
	common.addDir(name, "{0}/mako-vod-wiz-easy-to-think".format(baseUrl), 1, os.path.join(imagesDir, 'kids.jpg'), infos={"Title": name, "Plot": "צפיה בתכניות מערוץ WIZ"}, module=module)
	name = "לייף סטייל"
	common.addDir(name, "{0}/mako-vod-more/lifestyle".format(baseUrl), 1, os.path.join(imagesDir, 'lifestyle.jpg'), infos={"Title": name, "Plot": "צפיה בתכניות לייף סטייל"}, module=module)
	name = "אוכל"
	common.addDir(name, "{0}/mako-vod-special/cook-with-keshet".format(baseUrl), 1, os.path.join(imagesDir, 'lifestyle.jpg'), infos={"Title": name, "Plot": "צפיה בתכניות בנושא אוכל"}, module=module)
	name = "דוקומנטרי - תכניות"
	common.addDir(name, "{0}/mako-vod-more/docu_tv".format(baseUrl), 1, os.path.join(imagesDir, 'docu.jpg'), infos={"Title": name, "Plot": "צפיה בתכנים דוקומנטריים"}, module=module)
	name = "דוקומנטרי - סרטים"
	common.addDir(name, "{0}/mako-vod-more/docu_tv".format(baseUrl), 1, os.path.join(imagesDir, 'docu.jpg'), infos={"Title": name, "Plot": "צפיה בתכנים דוקומנטריים"}, module=module)
	name = "הופעות"
	common.addDir(name, "{0}/mako-vod-more/concerts".format(baseUrl), 1, os.path.join(imagesDir, 'live-music.jpg'), infos={"Title": name, "Plot": "צפיה בהופעות חיות"}, module=module)
	name = "הרצאות"
	common.addDir(name, "{0}/mako-vod-more/lectures".format(baseUrl), 1, os.path.join(imagesDir, 'lectures.jpg'), infos={"Title": name, "Plot": "צפיה בהרצאות"}, module=module)
	name = "חדשות 2"
	common.addDir(name, "news", 20, os.path.join(imagesDir, 'news.jpg'), infos={"Title": name, "Plot": "צפיה בחדשות ערוץ 2"}, module=module)

def GetSeriesList(catName, url, iconimage):
	url = "{0}&{1}".format(url, endings) if "?" in url else "{0}?{1}".format(url, endings)
	prms = GetJson(url)
	if prms is None:
		"Cannot get {0} list".format(catName)
		return
	key2 = None
	picKey = "picI"
	if catName == "תכניות MakoTV":
		key1 = "allPrograms"
		picKey = "picVOD"
	elif catName == "תכניות ילדים":
		key1 = "kidsPrograms"
	elif catName == "קלטות ילדים":
		key1 = "kidsCassettes"
	elif catName == "ילדים - WIZ" or catName == "ילדים - חינוכית" or catName == "אוכל":
		key1 = "specialArea"
		key2 = "items"
	elif "חדשות 2" in catName:
		key1 = "newsData"
		key2 = "list"
	elif catName == "הופעות" or catName == "הרצאות" or catName == "דוקומנטרי - סרטים":
		key1 = "moreVOD"
		key2 = "items"
	else:
		key1 = "moreVOD"
		key2 = "programItems"
	if key2 is None:
		series = prms.get(key1, {})
	else:
		series = prms.get(key1, {}).get(key2, {})
	seriesCount = len(series)
	for serie in series:
		try:
			mode = 2
			title = serie.get("title", "").strip().encode("utf-8")
			name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), title)
			subtitle = serie.get("subtitle", "").strip().encode("utf-8")
			url = serie.get("url", "")
			if url == "":
				url = serie.get("link", "")
				if url == "" and 'omri-gordon' in serie.get("lastEpisodeLink", ""):
					url = '/mako-vod-keshet/omri-gordon'
					name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), 'החדש של עומרי גורדון')
			url = "{0}{1}".format(baseUrl, url)
			if "VOD-" in url:
				mode = 5 
				if subtitle != "":
					name = "{0} - [COLOR {1}]{2}[/COLOR]".format(name, Addon.getSetting("chColor"), subtitle)
			icon = GetImage(serie, picKey, iconimage)
			description = serie.get("brief", "").strip().encode("utf-8")
			if serie.has_key("plot"):
				description = "{0} - {1}".format(description, serie["plot"].strip().encode("utf-8"))
			if "חדשות 2" in catName:
				name = '[COLOR {0}]{1}[/COLOR] - [COLOR {2}]{3}[/COLOR]'.format(Addon.getSetting("prColor"), serie.get("label", "").strip().encode("utf-8"), Addon.getSetting("chColor"), title)
				description = subtitle
			infos = {"Title": name, "Plot": description}
			if mode == 2:
				common.addDir(name, url, 2, icon, infos, module=module, totalItems=seriesCount)
			else:
				common.addDir(name, url, 5, icon, infos, contextMenu=[(common.GetLocaleString(30005), 'XBMC.RunPlugin({0}?url={1}&name={2}&mode=5&iconimage={3}&moredata=choose&module=keshet)'.format(sys.argv[0], urllib.quote_plus(url), urllib.quote_plus(name), urllib.quote_plus(icon)))], moreData='best', module='keshet', isFolder=False, isPlayable=True)
		except Exception as ex:
			xbmc.log(str(ex), 3)

def GetImage(prm, picKey, iconimage):
	icon = prm.get(picKey)
	if icon is None or icon == 'null' or icon == '':
		icon = prm.get('picC')
	if icon is None or icon == 'null' or icon == '':
		icon = prm.get('picB')
	if icon is None or icon == 'null' or icon == '':
		icon = prm.get('pic')
	if icon is None or icon == 'null' or icon == '':
		icon = prm.get('picUrl')
	return common.GetImageUrl(icon) if icon is not None else iconimage

def GetSeasonsList(url, iconimage):
	url = "{0}&{1}".format(url, endings) if "?" in url else "{0}?{1}".format(url, endings)
	prms = GetJson(url)
	if prms is None or not prms.has_key("programData") or not prms["programData"].has_key("seasons"):
		xbmc.log("Cannot get Seasons list", 2)
		return
	if iconimage == os.path.join(imagesDir, 'search.jpg'):
		iconimage = GetImage(prms["programData"], "picI", iconimage)
	for prm in prms["programData"]["seasons"]:
		try:
			if not prm.has_key("vods"):
				continue
			name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("timesColor"), prm.get('name', '').encode("utf-8"))
			url = "{0}{1}".format(baseUrl, prm["url"])
			description = prm.get('brief', '').encode("utf-8")
			infos = {"Title": name, "Plot": description}
			common.addDir(name, url, 3, iconimage, infos, module=module)
		except Exception as ex:
			xbmc.log(str(ex), 3)

def GetEpisodesList(url, icon):
	url = "{0}&{1}".format(url, endings) if "?" in url else "{0}?{1}".format(url, endings)
	prms = GetJson(url)
	if prms is None or not prms.has_key("channelId") or not prms.has_key("programData") or not prms["programData"].has_key("seasons"):
		xbmc.log("Cannot get Seasons list", 2)
		return
	videoChannelId=prms["channelId"]
	for prm in prms["programData"]["seasons"]:
		if prm is None or not prm.has_key("vods") or not prm.has_key("current") or prm["current"].lower() != "true":
			continue
		episodesCount = len(prm["vods"])
		for episode in prm["vods"]:
			try:
				vcmid = episode["guid"]
				name = '[COLOR {0}]{1}[/COLOR] - [COLOR {2}]{3}[/COLOR]'.format(Addon.getSetting("prColor"), episode["title"].encode("utf-8"), Addon.getSetting("chColor"), episode["shortSubtitle"].encode("utf-8"))
				url = "{0}/VodPlaylist?vcmid={1}&videoChannelId={2}".format(baseUrl, vcmid, videoChannelId)
				iconimage = GetImage(episode, 'picI', icon)
				description = episode.get('subtitle', '').encode("utf-8")
				infos = {"Title": name, "Plot": description, "Aired": episode["date"][episode["date"].find(' ')+1:]}
				common.addDir(name, url, 4, iconimage, infos, contextMenu=[(common.GetLocaleString(30005), 'XBMC.RunPlugin({0}?url={1}&name={2}&mode=4&iconimage={3}&moredata=choose&module=keshet)'.format(sys.argv[0], urllib.quote_plus(url), urllib.quote_plus(name), urllib.quote_plus(iconimage)))], moreData='best', module='keshet', isFolder=False, isPlayable=True)
			except Exception as ex:
				xbmc.log(str(ex), 3)

def GetChannels(url, iconimage):
	html = common.OpenURL(url, headers={"User-Agent": UA})
	if html == "":
		return None
	match = re.compile("var makoliveJson ='(.*?)';").findall(html)
	resultJSON = json.loads(match[0])
	if resultJSON is None or len(resultJSON) < 1:
		return None
	for channel in resultJSON['list']:
		name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("prColor"), channel['title'].encode("utf-8"))
		infos = {"Title": name, "Plot": channel['subtitle'].encode("utf-8")}
		url = '{0}{1}'.format(baseUrl, channel['link'])
		iconimage = channel['picUrl']
		common.addDir(name, url, 5, iconimage, infos, contextMenu=[(common.GetLocaleString(30005), 'XBMC.RunPlugin({0}?url={1}&name={2}&mode=5&iconimage={3}&moredata=choose&module=keshet)'.format(sys.argv[0], urllib.quote_plus(url), urllib.quote_plus(name), urllib.quote_plus(iconimage)))], moreData='best', module='keshet', isFolder=False, isPlayable=True)

def WatchLive(url, name='', iconimage='', quality='best'):
	channels = {
		'12': '{0}/mako-vod-live-tv/VOD-6540b8dcb64fd31006.htm'.format(baseUrl),
		'24': '{0}/mako-vod-live-tv/VOD-b3480d2eff3fd31006.htm'.format(baseUrl),
		'keshetBest': '{0}/mako-vod-live-tv/VOD-49a6215abae1b51006.htm'.format(baseUrl)
	}
	PlayItem(channels[url], name, iconimage, quality)
	
def PlayItem(url, name='', iconimage='', quality='best'):
	url = "{0}&{1}".format(url, endings) if "?" in url else "{0}?{1}".format(url, endings)
	prms = GetJson(url)
	if prms is None or not prms.has_key("video"):
		xbmc.log("Cannot get item", 2)
		return
	iconimage = GetImage(prms["video"], 'pic_I', iconimage)
	videoChannelId=prms["channelId"]
	vcmid = prms["video"]["guid"]
	url = "{0}/VodPlaylist?vcmid={0}&videoChannelId={1}".format(vcmid,videoChannelId)
	Play(url, name, iconimage, quality)

def Play(url, name='', iconimage='', quality='best'):
	common.DelCookies()
	headers={"User-Agent": UA}
	dv = url[url.find('vcmid=')+6: url.find('&videoChannelId=')]
	ch = url[url.find('&videoChannelId=')+16:]
	text = common.OpenURL('{0}/AjaxPage?jspName=playlist.jsp&vcmid={1}&videoChannelId={2}&consumer=web&encryption=no'.format(baseUrl, dv, ch), headers=headers)
	media = json.loads(text)['media']
	link, cookie_jar = GetLink(media, 'AKAMAI', dv, headers, quality)
	if link is None:
		link, cookie_jar = GetLink(media, 'CASTTIME', dv, headers, quality)
		if link is None:
			return None
	cookies = ";".join(['{0}'.format(urllib.quote('{0}={1}'.format(_cookie.name, _cookie.value))) for _cookie in cookie_jar])
	final = '{0}|User-Agent={1}&Cookie={2}'.format(link, UA, cookies)
	common.PlayStream(final, quality, name, iconimage)

def GetLink(media, cdn, dv, headers, quality):
	url = ''
	for item in media:
		if item['format'] == '{0}_HLS'.format(cdn.upper()):
			url = item['url']
			break
	if url == '':
		return None, None
	if username.strip() == '':
		l = 'http://mass.mako.co.il/ClicksStatistics/entitlementsServicesV2.jsp?et=gt&rv={0}&lp={1}'.format(cdn, url)
	else:
		l = 'http://mass.mako.co.il/ClicksStatistics/entitlementsServicesV2.jsp?et=gt&na=2.0&da=6gkr2ks9-4610-392g-f4s8-d743gg4623k2&du={0}&dv={1}&rv={2}&lp={3}'.format(deviceID, dv, cdn, url)
	ticket = GetTicket(l, headers)
	if url.startswith('//'):
		url = 'http:{0}'.format(url)
	cookie_jar = cookielib.LWPCookieJar()
	link = common.GetStreams('{0}?{1}'.format(url, ticket), headers=headers, CookieJar=cookie_jar, quality=quality)
	return link, cookie_jar

def GetTicket(link, headers):
	text = common.OpenURL(link, headers=headers)
	result = json.loads(text)
	if result['caseId'] == '4':
		result = Login()
		text = common.OpenURL(link, headers=headers)
		result = json.loads(text)
		if result['caseId'] != '1':
			xbmc.executebuiltin("XBMC.Notification({0}, You need to pay if you want to watch this video., {1}, {2})".format(AddonName, 5000 ,icon))
			return
	elif result['caseId'] != '1':
		xbmc.executebuiltin("XBMC.Notification({0}, Cannot get access for this video., {1}, {2})".format(AddonName, 5000 ,icon))
		return
	return urllib.unquote_plus(result['tickets'][0]['ticket'])

def Login():
	headers={"User-Agent": UA}
	link = 'http://mass.mako.co.il/ClicksStatistics/entitlementsServicesV2.jsp?eu={0}&da=6gkr2ks9-4610-392g-f4s8-d743gg4623k2&dwp={1}&et=ln&du={2}'
	text = common.OpenURL(link.format(username, password, deviceID), headers=headers)
	result = json.loads(text)
	if result['caseId'] != '1':
		return result
	link = 'http://mass.mako.co.il/ClicksStatistics/entitlementsServicesV2.jsp?da=6gkr2ks9-4610-392g-f4s8-d743gg4623k2&et=gds&du={0}'
	text = common.OpenURL(link.format(deviceID), headers=headers)
	result = json.loads(text)
	return result

def ShowYears(iconimage):
	for year in range(date.today().year, 2007, -1):
		name = '[B][COLOR {0}]חדשות 2 לשנת {1}[/COLOR][/B]'.format(Addon.getSetting("timesColor"), year)
		common.addDir(name, str(year), 21, iconimage, {"Title": name, "Plot": "צפיה ב{0}".format(common.GetUnColor(name))}, module=module)

def ShowMonthes(year, iconimage):
	fromMonth = 12 if date.today().year != int(year) else date.today().month
	toMonth = 0 if year != '2008' else 4
	for month in range(fromMonth, toMonth, -1):
		name = '[B][COLOR {0}]חדשות 2 לחודש {1:02d}-{2}[/COLOR][/B]'.format(Addon.getSetting("timesColor"), month, year)
		common.addDir(name, '{0}/mako-vod-channel2-news/{1}-{2:02d}'.format(baseUrl, year, month), 1, iconimage, {"Title": name, "Plot": "צפיה ב{0}".format(common.GetUnColor(name))}, module=module)

def GetJson(url):
	html = common.OpenURL(url, headers={"User-Agent": UA})
	if html == "":
		return None
	resultJSON = json.loads(html)
	if resultJSON is None or len(resultJSON) < 1:
		return None
	if resultJSON.has_key("root"):
		return resultJSON["root"]
	else:
		return resultJSON

def Search(url, iconimage):
	search_entered =''
	keyboard = xbmc.Keyboard(search_entered, 'מילים לחיפוש')
	keyboard.doModal()
	if keyboard.isConfirmed():
		search_entered = keyboard.getText()
	if search_entered !='':
		url = url.format(search_entered.replace(' ', '%20'))
		params = GetJson(url)
		suggestions = params["suggestions"]
		data = params["data"]
		for i in range(len(suggestions)):
			if "mako-vod-channel2-news" in data[i]:
				continue
			url = "{0}{1}".format(baseUrl, data[i])
			name = common.UnEscapeXML(suggestions[i]).encode("utf-8")
			infos={"Title": name, "Plot": name}
			if "VOD-" in data[i]:
				name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("chColor"), name)
				common.addDir(name, url, 5, iconimage, infos, contextMenu=[(common.GetLocaleString(30005), 'XBMC.RunPlugin({0}?url={1}&name={2}&mode=5&iconimage={3}&moredata=choose&module=keshet)'.format(sys.argv[0], urllib.quote_plus(url), urllib.quote_plus(name), urllib.quote_plus(iconimage)))], moreData='best', module='keshet', isFolder=False, isPlayable=True)
			else:
				name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), name)
				common.addDir(name, url, 2, iconimage, infos, module=module)
	else:
		return

def Run(name, url, mode, iconimage='', moreData=''):
	if mode == 0:
		GetCategoriesList(iconimage)
	elif mode == 1:	#------------- Series: -----------------
		GetSeriesList(name, url, iconimage)
	elif mode == 2:	#------------- Seasons: -----------------
		GetSeasonsList(url, iconimage)
	elif mode == 3:	#------------- Episodes: -----------------
		GetEpisodesList(url, iconimage)
	elif mode == 4:	#------------- Playing episode  -----------------
		Play(url, name, iconimage, moreData)
	elif mode == 5:	#------------- Playing item: -----------------
		if moreData == '':
			moreData = 'best'
		PlayItem(url, name, iconimage, moreData)
	elif mode == 6:	#------------- Search items: -----------------
		Search(url, iconimage)
	elif mode == 7:	#------------- Toggle Lists' sorting method: -----------------
		common.ToggleSortMethod('makoSortBy', sortBy)
	elif mode == 8:
		GetChannels(url, iconimage)
	elif mode == 10:
		WatchLive(url, name, iconimage, moreData)
	elif mode == 20:
		ShowYears(iconimage)
	elif mode == 21:
		ShowMonthes(url, iconimage)
		
	common.SetViewMode('episodes')
	if sortBy == 1 and mode != 0 and mode != 6:
		xbmcplugin.addSortMethod(handle, 1)
