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

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

def WatchLive(url, name='', iconimage='', quality='best'):
	channels = {
		'i24en': 'http://www.i24news.tv/en/tv/live',
		'i24fr': 'http://www.i24news.tv/fr/tv/live',
		'i24ar': 'http://www.i24news.tv/ar/tv/live'
	}
	headers={"User-Agent": userAgent}
	text = common.OpenURL(channels[url], headers=headers)
	match = re.compile("__STORES__ = '(.*?)'").findall(text)
	a2 = json.loads(base64.b64decode(match[0]))
	text = common.OpenURL('http://www.dailymotion.com/embed/video/{0}'.format(a2['LiveVideoStore']['video']['hash']), headers=headers)
	match = re.compile('"stream_chromecast_url":"(.*?)"').findall(text)
	link = common.OpenURL('{0}&redirect=0'.format(match[0].replace('\\','')), 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 == 10:
		WatchLive(url, name, iconimage, moreData)
		
	common.SetViewMode('episodes')