# -*- coding: utf-8 -*-
import xbmc, xbmcaddon
import sys, re, json, urllib
import collections
import resources.lib.common as common

handle = int(sys.argv[1])
AddonID = 'plugin.video.idanplus'
Addon = xbmcaddon.Addon(AddonID)
sortBy = int(Addon.getSetting("reshetSortBy"))
module = 'reshet'
userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"

def GetUrlJson(url):
	result = {}
	try:
		text = common.OpenURL(url, headers={"User-Agent": userAgent})
		data_query = re.compile('initial_data = \{(.*?)\};').findall(text)
		result = json.loads('{' + data_query[0] + '}')['data_query'] if len(data_query) > 0 else {}
	except Exception as ex:
		xbmc.log(str(ex), 3)
	return result

def GetSeriesList(iconimage):
	sortString = common.GetLocaleString(30002) if sortBy == 0 else common.GetLocaleString(30003)
	name = "{0}: {1}".format(common.GetLocaleString(30001), sortString)
	common.addDir(name, "toggleSortingMethod", 5, 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 = 'http://reshet.tv/vod/'
	result = GetUrlJson(url)
	if len(result) < 1:
		return
	grids_arr = []
	seriesIDs = []
	grids = result.get('Content', {}).get('PageGrid', {})
	for grid in grids:
		for seriesID in grid.get('Posts', {}):
			if seriesID in seriesIDs or seriesID == 13555 or seriesID == 170768 or seriesID == 594364:
				continue
			seriesIDs.append(seriesID)
			serie = result.get('ItemStore', {}).get(str(seriesID), {})
			link = serie.get('link')
			if link is None or 'item' in link:
				continue
			name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), serie['title'].encode('utf-8'))
			pageTitle = serie.get('pageTitle', {})
			description = name if pageTitle is None else pageTitle.get('description'.encode('utf-8'), name)
			if sortBy == 1:
				grids_arr.append((name, link, serie['images']['app_16x9'].encode('utf-8'), {"Title": name, "Plot": description}))
			else:
				common.addDir(name, link, 1, serie['images']['app_16x9'].encode('utf-8'), infos={"Title": name, "Plot": description}, module=module)
	if sortBy == 1:
		grids_sorted = sorted(grids_arr,key=lambda grids_arr: grids_arr[0])
		for name, link, icon, infos in grids_sorted:
			common.addDir(name, link, 1, icon, infos=infos, module=module)
	
def GetSeasonList(url, iconimage):
	result = GetUrlJson(url)
	seasons, episodes = GetLinks(result, iconimage)
	if len(seasons) > 0:
		for link, title in seasons.iteritems():
			name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("timesColor"), title)
			common.addDir(name, link, 2, iconimage, infos={"Title": name}, module=module)
		if len(episodes) < 1:
			return
	ShowEpisodes(episodes, iconimage)

def GetEpisodesList(url, iconimage):
	result = GetUrlJson(url)
	seasons, episodes = GetLinks(result, iconimage)
	if 'http://reshet.tv/news/tonight/season-01/episodes/' in seasons:
		name = 'אין פרקים מלאים'
		common.addDir(name, '', 99, iconimage, infos={"Title": name}, module=module, isFolder=False)
		return
	ShowEpisodes(episodes, iconimage)
	ShowPaging(result.get('Content', {}).get('PageGrid', {}), result.get('PageMeta', {}).get('page_url', ''), iconimage, 2)
	
def GetLinks(result, iconimage):
	seasons = {} if common.GetPyVer() < '2.7' else collections.OrderedDict()
	episodes = []
	subMenus = result.get('Header', {}).get('subMenu', {})
	if subMenus:
		for subMenu in subMenus:
			try:
				title = subMenu.get('title')
				link = subMenu.get('url')
				ending = link[link.rfind('/', 0, len(link)-1):]
				if 'episodes' in ending or 'season' in ending and (link not in seasons or seasons[link] == ''):
					seasons[link] = title.strip().encode('utf-8')
			except Exception as ex:
				xbmc.log(str(ex), 3)
	grids = result.get('Content', {}).get('PageGrid', {})
	for grid in grids:
		title = grid.get('GridTitle')
		gridTitle = '' if title is None else title.get('title', '').strip().encode('utf-8')
		titleLink = '' if title is None else title.get('link', '')
		gridLink = '' if titleLink is None else titleLink.strip().encode('utf-8')
		if 'episodes' in gridLink and (gridLink not in seasons or seasons[gridLink] == ''):
			seasons[gridLink] = gridTitle if gridTitle != '' else result.get('PageMeta', {}).get('title', '').strip().encode('utf-8')
		for pid in grid.get('Posts', {}):
			try:
				post = result.get('ItemStore', {}).get(str(pid), {})
				link = post['link'].replace('vod-2', 'vod').replace('/channel2/', '/channel2-news/')
				if 'episodes' not in link:
					ending = link[link.rfind('/', 0, len(link)-1):]
					if 'season' in ending and (link not in seasons or seasons[link] == ''):
						seasons[link] = post.get('title', '').strip().encode('utf-8')
					continue
				if 'links' in post['postType'] and link not in seasons:
					seasons[link] = post.get('title', '').strip().encode('utf-8')
				else:
					seasonsLink = link[:link.find('/episodes/') + 10].replace('/item', '')
					match = re.compile('/season-(\d+)(.*?)/').findall(seasonsLink)
					if len(match) > 0 and match[0][1] != '':
						seasonsLink = seasonsLink.replace(match[0][1], '')
					if seasonsLink not in seasons:
						page_2_level_heb = post['coolaData'].get('page_2_level_heb')
						page_2_level_heb = '' if page_2_level_heb is None else page_2_level_heb.encode('utf-8')
						page_3_level_heb = post['coolaData'].get('page_3_level_heb')
						page_3_level_heb = '' if page_3_level_heb is None else page_3_level_heb.encode('utf-8')
						page_4_level_heb = post['coolaData'].get('page_4_level_heb')
						page_4_level_heb = '' if page_4_level_heb is None else page_4_level_heb.encode('utf-8')
						seasons[seasonsLink] = '{0} {1} {2}'.format(page_2_level_heb, page_3_level_heb, page_4_level_heb)
					video = post.get('video')
					if video is None or video.get('videoID') is None:
						continue
					videoID = video['videoID']
					icon =  post['images'].get('app_16x9', iconimage).encode('utf-8')
					episodes.append((gridTitle, videoID, icon, post.get('title', '').strip().encode('utf-8'), post.get('subtitle', '').strip().encode('utf-8'), post.get('publishDate')))
			except Exception as ex:
				xbmc.log(str(ex), 3)
	return seasons, episodes

def ShowEpisodes(episodes, iconimage):
	if len(episodes) < 1:
		name = 'אין פרקים מלאים'
		common.addDir(name, '', 99, iconimage, infos={"Title": name}, module=module, isFolder=False)
		return
	for gridTitle, link, icon, title, subtitle, publishDate in episodes:
		name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("chColor"), title) if gridTitle is None or gridTitle == '' else '[COLOR {0}]{1}[/COLOR] - [COLOR {2}]{3}[/COLOR]'.format(Addon.getSetting("prColor"), gridTitle, Addon.getSetting("chColor"), title)
		common.addDir(name, link, 3, icon, infos={"Title": name, "Plot": subtitle, "Aired": publishDate}, contextMenu=[(common.GetLocaleString(30005), 'XBMC.RunPlugin({0}?url={1}&name={2}&mode=3&iconimage={3}&moredata=choose&module=reshet)'.format(sys.argv[0], urllib.quote_plus(link), urllib.quote_plus(name), urllib.quote_plus(icon)))], moreData='best', module=module, isFolder=False, isPlayable=True)

def ShowPaging(grids, page_url, iconimage, mode):
	WpQuery = grids[0].get('WpQuery', None)
	if WpQuery is None:
		paged = 0  
	else: 
		paged = WpQuery.get('paged', 0)
	if paged > 0 and  len(grids) > 0:
		max_page = grids[0].get('max_page', 0)
		if max_page > paged:
			common.addDir('[COLOR green]Next Page[/COLOR]', page_url + 'page/' + str(paged+1) + '/', mode, iconimage, module=module)
		if paged > 1:
			prev_page = page_url + 'page/' + str(paged-1) + '/' if paged - 1 > 1 else page_url
			common.addDir('[COLOR green]Prev Page[/COLOR]', prev_page, mode, iconimage, module=module)

def Play(url, name='', iconimage='', quality='best'):
	try:
		#url = 'http://c.brightcove.com/services/mobile/streaming/index/master.m3u8?videoId={0}'.format(url)
		headers={"Accept": "application/json;pk=BCpkADawqM30eqkItS5d08jYUtMkbTKu99oEBllbfUaFKeknXu4iYsh75cRm2huJ_b1-pXEPuvItI-733TqJN1zENi-DcHlt7b4Dv6gCT8T3BS-ampD0XMnORQLoLvjvxD14AseHxvk0esW3", "User-Agent": userAgent}
		result = common.OpenURL('https://edge.api.brightcove.com/playback/v1/accounts/1551111274001/videos/{0}'.format(url), headers=headers)
		sources = json.loads(result)['sources']
		link = ''
		avg_bitrate = 0
		for source in sources:
			if 'src' in source:
				if source['container'] == 'M2TS':
					link = common.GetStreams(source['src'], headers=headers, quality=quality)
					break
				if source['avg_bitrate'] > avg_bitrate:
					link = source['src']
					avg_bitrate = source['avg_bitrate']
					#xbmc.log('[{0}]  {1}'.format(avg_bitrate, link), 5)
		final = '{0}|User-Agent={1}'.format(link, userAgent)
		common.PlayStream(final, quality, name, iconimage)
	except Exception as ex:
		xbmc.log(str(ex), 3)

def WatchLive(name='', iconimage='', quality='best'):
	referer = 'http://reshet.tv/live/'
	if common.GetPyVer() >= '2.7.9':
		headers={"Accept": "application/json;pk=BCpkADawqM30eqkItS5d08jYUtMkbTKu99oEBllbfUaFKeknXu4iYsh75cRm2huJ_b1-pXEPuvItI-733TqJN1zENi-DcHlt7b4Dv6gCT8T3BS-ampD0XMnORQLoLvjvxD14AseHxvk0esW3", "User-Agent": userAgent}
		result = common.OpenURL('https://edge.api.brightcove.com/playback/v1/accounts/1551111274001/videos/ref:stream_reshet_live1', headers=headers)
		headers={"User-Agent": userAgent, 'Referer': referer}
		link = common.GetStreams(json.loads(result)['sources'][0]['src'], headers=headers, quality=quality)
	else:
		link = 'https://besttv1.aoslive.it.best-tv.com/reshet/studio/index.m3u8'
	final = '{0}|User-Agent={1}&Referer={2}'.format(link, userAgent, referer)
	common.PlayStream(final, quality, name, iconimage)

def Run(name, url, mode, iconimage='', moreData=''):
	if mode == 0:
		GetSeriesList(iconimage)						# Series
	elif mode == 1:
		GetSeasonList(url, iconimage)					# Seasons
	elif mode == 2:
		GetEpisodesList(url, iconimage)					# Episodes
	elif mode == 3:
		Play(url, name, iconimage, moreData)			# Playing episode
	elif mode == 4:
		WatchLive(name, iconimage, moreData)			# Playing Live
	elif mode == 5:	
		common.ToggleSortMethod('reshetSortBy', sortBy)	# Toggle Lists' sorting method
	
	common.SetViewMode('episodes')
