# -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcplugin, xbmcaddon
import sys, os, re, urlparse
import resources.lib.common as common

handle = int(sys.argv[1])
AddonID = 'plugin.video.idanplus'
Addon = xbmcaddon.Addon(AddonID)
icon = Addon.getAddonInfo('icon')
imagesDir = xbmc.translatePath(os.path.join(Addon.getAddonInfo('path'), 'resources', 'images')).decode("utf-8")
sortBy = int(Addon.getSetting("kanSortBy"))
module = 'kan'
baseUrl = 'https://www.kan.org.il'
userAgent = common.GetUserAgent()
headers={"User-Agent": userAgent}

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", 4, 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)
	name = 'תוכניות בידור ותרבות'
	common.addDir(name, '{0}/Page.aspx?landingPageId=1039'.format(baseUrl), 1, iconimage, infos={"Title": name}, module=module)
	name = 'סרטי דוקו'
	common.addDir(name, '1076', 2, iconimage, infos={"Title": name}, module=module)
	name = 'תכניות מהעולם'
	common.addDir(name, '{0}/page.aspx?landingPageId=1059'.format(baseUrl), 1, iconimage, infos={"Title": name}, module=module)
	name = 'רצועת האקטואליה'
	common.addDir(name, '{0}/page.aspx?landingPageId=1037'.format(baseUrl), 1, iconimage, infos={"Title": name}, module=module)
	name = 'דיגיטל'
	common.addDir(name, '{0}/page.aspx?landingPageId=1041'.format(baseUrl), 1, iconimage, infos={"Title": name}, module=module)
	name = 'תכניות רדיו'
	common.addDir(name, '', 21, iconimage, infos={"Title": name}, module=module)

def GetSeriesList(url):
	text = common.OpenURL(url)
	matches = re.compile('class="component_sm_item news w-clearfix.+?href=\'.+?/program/\?catId=(.+?)\'.+?url\(\'(.+?)\'.+?<h3.+?>(.*?)</h3>.+?<p.+?>(.*?)</p>', re.S|re.I).findall(text)
	for id, iconimage, name, description in matches:
		name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), name.strip())
		common.addDir(name, id, 2, '{0}{1}'.format(baseUrl, iconimage), infos={"Title": name, "Plot": description}, module=module)
	matches = re.compile('<div class="it_small_pictgroup.+?"background-image: url\(\'(.+?)\'\);.+?href=".+?/Program/\?catId=(.+?)".+?class="it_small_title">(.*?)</div>.+?class="it_small_txt">(.*?)</div>', re.S).findall(text)
	for iconimage, id, name, description in matches:
		name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), name.strip())
		common.addDir(name, id, 2, '{0}{1}'.format(baseUrl, iconimage), infos={"Title": name, "Plot": description.strip()}, module=module)

def GetEpisodesList(catId):
	i = 0
	while True:
		i += 1
		url = '{0}/Program/getMoreProgram.aspx?count={1}&catId={2}'.format(baseUrl, i, catId)
		text = common.OpenURL(url)
		matches = re.compile('w-clearfix">.*?url\(\'(.+?)\'.+?<iframe.+?src="(.+?)".+?"content_title">(.+?)</.+?<p>(.+?)</p>', re.S).findall(text)
		if len(matches) == 0:
			break
		for iconimage, url, name, description in matches:
			name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("chColor"), name.strip())
			common.addDir(name, url, 3, '{0}{1}'.format(baseUrl, iconimage), infos={"Title": name, "Plot": description.replace('&nbsp;', '').strip()}, module=module, isFolder=False, isPlayable=True)

def GetRadioCategoriesList(iconimage):
	name = 'כאן ב'
	common.addDir(name, '{0}/live/radio.aspx?stationid=3'.format(baseUrl), 22, os.path.join(imagesDir, "bet.png"), infos={"Title": name}, module=module)
	name = 'כאן גימל'
	common.addDir(name, '{0}/live/radio.aspx?stationid=9'.format(baseUrl), 22, os.path.join(imagesDir, "gimel.png"), infos={"Title": name}, module=module)
	name = 'כאן 88'
	common.addDir(name, '{0}/live/radio.aspx?stationid=4'.format(baseUrl), 22, os.path.join(imagesDir, "88.png"), infos={"Title": name}, module=module)
	name = 'כאן תרבות'
	common.addDir(name, '{0}/live/radio.aspx?stationid=5'.format(baseUrl), 22, os.path.join(imagesDir, "culture.png"), infos={"Title": name}, module=module)
	name = 'כאן קול המוסיקה'
	common.addDir(name, '{0}/live/radio.aspx?stationid=7'.format(baseUrl), 22, os.path.join(imagesDir, "music.png"), infos={"Title": name}, module=module)
	name = 'כאן מורשת'
	common.addDir(name, '{0}/live/radio.aspx?stationid=6'.format(baseUrl), 22, os.path.join(imagesDir, "moreshet.png"), infos={"Title": name}, module=module)
	name = 'כאן Reka'
	common.addDir(name, '{0}/live/radio.aspx?stationid=10'.format(baseUrl), 22, os.path.join(imagesDir, "reka.png"), infos={"Title": name}, module=module)

def GetRadioSeriesList(url):
	text = common.OpenURL(url)
	matches = re.compile('class="radio_online_block">\s*?<a href=".*?progId=(.+?)" class="radio_online_pict.*?url\(\'(.*?)\'\);" alt="(.*?)".*?station_future_name">(.*?)</div>', re.S).findall(text)
	for id, iconimage, name, description in matches:
		name = '[B][COLOR {0}]{1}[/COLOR][/B]'.format(Addon.getSetting("prColor"), name.strip())
		common.addDir(name, id, 23, '{0}{1}'.format(baseUrl, iconimage), infos={"Title": name, "Plot": description}, module=module)

def GetRadioEpisodesList(progId, iconimage):
	i = 1
	while True:
		url = '{0}/Radio/getMoreItems.aspx?index={1}&progId={2}'.format(baseUrl, i, progId)
		text = common.OpenURL(url)
		matches = re.compile('class="radio_program_partgroup">.*?onclick="playItem\(\'(.*?)\'\)".*?class="radio_program_toggle top_plus.*?<div>(.*?)</div>', re.S).findall(text)
		for itemId, name in matches:
			name = '[COLOR {0}]{1}[/COLOR]'.format(Addon.getSetting("chColor"), name.strip())
			common.addDir(name, '{0}/radio/player.aspx?ItemId={1}'.format(baseUrl, itemId), 12, iconimage, infos={"Title": name}, module=module, moreData='best', isFolder=False, isPlayable=True)
		if len(matches) < 10:
			break
		i += 10

def Play(url, name='', iconimage='', quality='best'):
	if 'youtube' in url:
		video_id = url[url.rfind('/')+1:]
		if '?' in video_id:
			video_id = video_id[:video_id.find('?')]
		final = 'plugin://plugin.video.youtube/play/?video_id={0}'.format(video_id)
	else:
		link = GetPlayerKanUrl(url, headers=headers)
		final = '{0}|User-Agent={1}'.format(link, userAgent)
	listitem = xbmcgui.ListItem(path=final)
	xbmcplugin.setResolvedUrl(handle=handle, succeeded=True, listitem=listitem)

def GetPlayerKanUrl(url, headers={}):
	text = common.OpenURL(url, headers=headers)
	match = re.compile("var\s*metadataURL\s*?=\s*?'(.+?)'").findall(text)
	text = common.OpenURL(match[0], headers=headers)
	match = re.compile("<SmilURL.*>(.+)</SmilURL>").findall(text)
	smil = match[0].replace('amp;', '')
	match = re.compile("<Server priority='1'>(.+)</Server>").findall(text)
	server = match[0]
	link = urlparse.urlunparse(urlparse.urlparse(smil)._replace(netloc=server))
	return link

def WatchLive(url, name='', iconimage='', quality='best', type='video'):
	channels = {
		'11': '{0}/live/tv.aspx?stationId=2'.format(baseUrl),
		'33': '{0}/live/tv.aspx?stationId=14'.format(baseUrl),
		'bet': '{0}/live/radio.aspx?stationId=3'.format(baseUrl),
		'gimel': '{0}/live/radio.aspx?stationId=9'.format(baseUrl),
		'culture': '{0}/live/radio.aspx?stationId=5'.format(baseUrl),
		'88': '{0}/live/radio.aspx?stationId=4'.format(baseUrl),
		'moreshet':'{0}/live/radio.aspx?stationId=6'.format(baseUrl),
		'music': '{0}/live/radio.aspx?stationId=7'.format(baseUrl),
		'reka': '{0}/live/radio.aspx?stationId=10'.format(baseUrl),
		'makan': 'http://www.makan.org.il/live/radio.aspx?stationId=2',
		'persian': 'http://farsi.kan.org.il/',
		'80-90': '{0}/Radio/radio-80_90.aspx'.format(baseUrl),
		'alt': '{0}/Radio/radio-alt.aspx'.format(baseUrl),
		'classic': '{0}/Radio/radio-classic.aspx'.format(baseUrl),
		'hits': '{0}/Radio/radio-hits.aspx'.format(baseUrl),
		'nos': '{0}/Radio/radio-nos.aspx'.format(baseUrl),
		'regesh': '{0}/Radio/radio-regesh.aspx'.format(baseUrl),
		'oriental': '{0}/Radio/Oriental.aspx'.format(baseUrl)
	}
	channelUrl = url if type == 'radioProgram' else channels[url]
	text = common.OpenURL(channelUrl, headers=headers)
	if url == 'makan' or url == 'persian' or type == 'radioProgram':
		match = re.compile('id="playerFrame".*?src="(.*?)"', re.S).findall(text)
	elif type == 'video':
		match = re.compile('<iframe\s*class="embedly-embed"\s*src="(.+?)"').findall(text)
	else:
		match = re.compile('iframeLink\s*?=\s*?"(.*)"').findall(text)
	link = GetPlayerKanUrl(match[0], headers=headers)
	link = common.GetStreams(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)
	elif mode == 2:	#------------- Episodes: ------------------------
		GetEpisodesList(url)
	elif mode == 3:	#------------- Playing episode  -----------------
		Play(url, name, iconimage, moreData)
	elif mode == 4:	#------------- Toggle Lists' sorting method -----
		common.ToggleSortMethod('kanSortBy', sortBy)
	elif mode == 21:	#----------- Radio Categories: ------------------
		GetRadioCategoriesList(iconimage)
	elif mode == 22:	#------------- Radio Series: --------------------
		GetRadioSeriesList(url)
	elif mode == 23:	#------------- Radio Episodes: ------------------
		GetRadioEpisodesList(url, iconimage)
	elif mode == 12:
		WatchLive(url, name, iconimage, moreData, type='radioProgram')
	elif mode == 10:
		WatchLive(url, name, iconimage, moreData, type='video')
	elif mode == 11:
		WatchLive(url, name, iconimage, moreData, type='radio')
		
	if mode != 0:
		common.SetViewMode('episodes')
	if sortBy == 1 and mode == 1:
		xbmcplugin.addSortMethod(handle, 1)