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

handle = int(sys.argv[1])
AddonID = 'plugin.video.idanplus'
Addon = xbmcaddon.Addon(AddonID)
module = '23tv'
userAgent = common.GetUserAgent()

def WatchLive(name='', iconimage='', quality='best'):
	headers={"User-Agent": userAgent}
	url = 'http://www.23tv.co.il/15-he/Tachi.aspx'
	text = common.OpenURL(url, headers=headers)
	#match = re.compile('id="Master_ContentPlaceHolder1_usBanners_234_rptDocs_ctl00_divMidKidum".*?onclick="window.open\(\'(.*?)\'\)"').findall(text)[0].replace('&amp;', '&')
	#match[0] = 'http://www.cast-tv.biz/play/?media=yes&clid=25400&movId=fgbhfm'
	#url = 'http://www.cast-tv.biz/play/getVideoJson.aspx?clid=25400&movId=fgbhfm&SkinID=mobile&jsoncallback=showjson&StreamType=hls&FirstTime=truematch
	match = re.compile("clid=(.*?)&amp;movId=(.*?)'").findall(text)
	text = common.OpenURL('http://www.cast-tv.biz/play/getVideoJson.aspx?clid={0}&movId={1}&SkinID=mobile&jsoncallback=showjson&StreamType=hls&FirstTime=truematch'.format(match[0][0], match[0][1]), headers=headers)
	resultJSON = json.loads(text)['movies'][0]['ratesData']
	link = common.GetStreams('{0}/_definst_/{1}'.format(resultJSON['serversList'][0], resultJSON['mainRate']), 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 == 10:
		WatchLive(name, iconimage, moreData)
		
	common.SetViewMode('episodes')