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

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

def WatchLive(name='', iconimage='', quality='best'):
	headers={"User-Agent": userAgent}
	url = 'http://main.knesset.gov.il/News/Broadcast/Pages/Channel99.aspx'
	cookie_jar = cookielib.LWPCookieJar()
	text = common.OpenURL(url, headers=headers, CookieJar=cookie_jar)
	cookies = ['{0}={1}'.format(_cookie.name, _cookie.value) for _cookie in cookie_jar]
	headers['Cookie'] = cookies[0][:cookies[0].find(';')]
	text = common.OpenURL(url, headers=headers)
	match = re.compile('<iframe src="(.+?)"').findall(text)
	headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
	text = common.OpenURL(match[0], headers=headers)
	match = re.compile('<script\s*type="text/javascript"\s*src="(.+?)"').findall(text)
	text = common.OpenURL(match[0], headers=headers)
	match = re.compile('"sources":.*?"file":\s*"(.+?)"', re.S).findall(text)
	link = common.GetStreams(match[0], 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')