# -*- 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 = 'glz'
userAgent = common.GetUserAgent()
headers={"User-Agent": userAgent}

class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
	def http_error_301(self, req, fp, code, msg, headers):
		result = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
		return result

	def http_error_302(self, req, fp, code, msg, headers):
		result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
		return result

def WatchLive(url, name='', iconimage='', quality='best'):
	channels = {
		'glz': '1051',
		'glglz': '1920'
	}
	url = 'https://glz.co.il/umbraco/api/player/getplayerdata?rootId={0}'.format(channels[url])
	text = common.OpenURL(url, headers=headers)
	data = json.loads(text)
	req = urllib2.Request(data['liveBroadcast']['fileUrl'], headers=headers)
	opener = urllib2.build_opener(SmartRedirectHandler())
	res = opener.open(req)
	link = res.url
	final = '{0}|User-Agent={1}'.format(link, userAgent)
	common.PlayStream(final, quality, name, iconimage)

def Run(name, url, mode, iconimage='', moreData=''):
	if mode == 11:
		WatchLive(url, name, iconimage, moreData)
		
	common.SetViewMode('episodes')