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

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")

params = dict(urlparse.parse_qsl(sys.argv[2].replace('?','')))
url = urllib.unquote_plus(params.get('url', ''))
mode = int(params.get('mode','-1'))
name = urllib.unquote_plus(params.get('name', ''))
iconimage = urllib.unquote_plus(params.get('iconimage', ''))
module = params.get('module')
moreData = urllib.unquote_plus(params.get('moredata', ''))

def GetCategoriesList():
	name = '[B]שידורים חיים[/B]'
	common.addDir(name, '', 1, icon, {"Title": name})
	name = '[B]VOD[/B]'
	common.addDir(name, '', 2, icon, {"Title": name})
	name = '[B]רדיו[/B]'
	common.addDir(name, '', 3, icon, {"Title": name})

def LiveChannels():
	name = '[B]קליק ימני על ערוץ להצגת מדריך מפורט[/B]'
	common.addDir(name, '', 99, icon, infos={"Title": name}, isFolder=False)
	name = '[B]רענון רשימה[/B]'
	common.addDir(name, '', 4, icon, infos={"Title": name}, isFolder=False)
	nowEPG = epg.GetNowEPG()
	LiveChannel('כאן 11', '11', 10, os.path.join(imagesDir, "kan.jpg"), 'kan', programs=nowEPG.get('11', []))
	LiveChannel('קשת 12', '12', 10, os.path.join(imagesDir, "keshet.jpg"), 'keshet', programs=nowEPG.get('12', []))
	LiveChannel('רשת 13', '13', 4, os.path.join(imagesDir, "13.png"), 'reshet', programs=nowEPG.get('13', []))
	LiveChannel('עשר 14', '14', 6, os.path.join(imagesDir, "ten.png"), 'ten', programs=nowEPG.get('14', []))
	LiveChannel('מורשת 20', '20', 10, os.path.join(imagesDir, "20.png"), 'twenty', programs=nowEPG.get('20', []))
	LiveChannel('חינוכית 23', '23', 10, os.path.join(imagesDir, "23tv.png"), '23tv', programs=nowEPG.get('23', []))
	LiveChannel('מוזיקה 24', '24', 10, os.path.join(imagesDir, "24.jpg"), 'keshet', programs=nowEPG.get('24', []))
	LiveChannel('מכאן 33', '33', 10, os.path.join(imagesDir, "makan.png"), 'kan', programs=nowEPG.get('33', []))
	LiveChannel('קבלה 66', '66', 10, os.path.join(imagesDir, "kabbalah.jpg"), 'kabbalah', programs=nowEPG.get('66', []))
	LiveChannel('מאיר 96', '96', 10, os.path.join(imagesDir, "meirtv.jpg"), 'meirtv', programs=nowEPG.get('96', []))
	LiveChannel('הידברות 97', '97', 10, os.path.join(imagesDir, "hidabroot.jpg"), 'hidabroot', programs=nowEPG.get('97', []))
	LiveChannel('כנסת 99', '99', 10, os.path.join(imagesDir, "knesset.png"), 'knesset', programs=nowEPG.get('99', []))
	LiveChannel('i24 English', 'i24en', 10, os.path.join(imagesDir, "i24.png"), 'i24', programs=nowEPG.get('i24en', []))
	LiveChannel('i24 French', 'i24fr', 10, os.path.join(imagesDir, "i24.png"), 'i24', programs=nowEPG.get('i24fr', []))
	LiveChannel('i24 Arabic', 'i24ar', 10, os.path.join(imagesDir, "i24.png"), 'i24', programs=nowEPG.get('i24ar', []))
	LiveChannel('קשת המיטב', 'keshetBest', 10, os.path.join(imagesDir, "keshet_best.jpg"), 'keshet')

def LiveChannel(name, url, mode, iconimage, module, choose=True, programs=[]):
	displayName = "[COLOR {0}][B]{1}[/B][/COLOR]".format(Addon.getSetting("chColor"), name)
	description = ''
	contextMenu = []
	if choose:
		contextMenu.append((common.GetLocaleString(30005), 'RunPlugin({0}?url={1}&name={2}&mode={3}&iconimage={4}&moredata=choose&module={5})'.format(sys.argv[0], url, urllib.quote_plus(name), mode, urllib.quote_plus(iconimage), module)))
	if len(programs) > 0:
		contextMenu.append(('EPG', 'Container.Update({0}?url={1}&name={2}&mode=2&iconimage={3}&module=epg)'.format(sys.argv[0], url, urllib.quote_plus(name), urllib.quote_plus(iconimage))))
		start_time = datetime.datetime.fromtimestamp(programs[0]["start"]).strftime('%H:%M')
		end_time = datetime.datetime.fromtimestamp(programs[0]["end"]).strftime('%H:%M')
		programName = "[COLOR {0}][B]{1}[/B][/COLOR] [COLOR {2}][{3}-{4}][/COLOR]".format(Addon.getSetting("prColor"), programs[0]["name"].encode('utf-8'), Addon.getSetting("timesColor"), start_time, end_time)
		displayName = "{0} - {1}".format(displayName, programName)
		description = '{0}[CR]{1}'.format(programName, programs[0]["description"].encode('utf-8'))
		if len(programs) > 1:
			description = '{0}[CR][CR]Next: [COLOR {1}][B]{2}[/B][/COLOR] [COLOR {3}][{4}-{5}][/COLOR]'.format(description, Addon.getSetting("prColor"), programs[1]["name"].encode('utf-8'), Addon.getSetting("timesColor"), datetime.datetime.fromtimestamp(programs[1]["start"]).strftime('%H:%M'), datetime.datetime.fromtimestamp(programs[1]["end"]).strftime('%H:%M'))
	if contextMenu == []:
		contextMenu = None
	common.addDir(displayName, url, mode, iconimage, infos={"Title": displayName, "Plot": description}, contextMenu=contextMenu, moreData='best', module=module, isFolder=False, isPlayable=True)

def VODs():
	name = 'כאן 11'
	common.addDir(name, '', 0, os.path.join(imagesDir, "kan.jpg"), infos={"Title": name}, module='kan')
	name = 'קשת 12'
	common.addDir(name, '', 0, os.path.join(imagesDir, "mako.png"), infos={"Title": name}, module='keshet')
	name = 'רשת 13'
	common.addDir(name, '', 0, os.path.join(imagesDir, "13.png"), infos={"Title": name}, module='reshet')
	name = 'עשר 14'
	common.addDir(name, '', 0, os.path.join(imagesDir, "ten.png"), infos={"Title": name}, module='ten')
	name = 'מורשת 20'
	common.addDir(name, '', 0, os.path.join(imagesDir, "20.png"), infos={"Title": name}, module='twenty')

def Radios():
	name = '[B]קליק ימני על ערוץ להצגת מדריך מפורט[/B]'
	common.addDir(name, '', 99, icon, infos={"Title": name}, isFolder=False)
	name = '[B]רענון רשימה[/B]'
	common.addDir(name, '', 4, icon, infos={"Title": name}, isFolder=False)
	nowEPG = epg.GetNowEPG()
	LiveChannel('גלגל"צ', 'glglz', 11, os.path.join(imagesDir, "glglz.jpg"), 'glz', choose=False, programs=nowEPG.get('glglz', []))
	LiveChannel('כאן 88', '88', 11, os.path.join(imagesDir, "88.png"), 'kan', choose=False, programs=nowEPG.get('88', []))
	LiveChannel('ECO 99FM', '99fm', 11, os.path.join(imagesDir, "99fm.png"), '99fm', choose=False, programs=nowEPG.get('99fm', []))
	LiveChannel('102FM רדיו תל אביב', '102fm', 11, os.path.join(imagesDir, "102fm.jpg"), '102fm', choose=False, programs=nowEPG.get('102fm', []))
	LiveChannel('103FM רדיו ללא הפסקה', '103fm', 11, os.path.join(imagesDir, "103fm.png"), '103fm', choose=False, programs=nowEPG.get('103fm', []))
	LiveChannel('גלי צה"ל', 'glz', 11, os.path.join(imagesDir, "glz.jpg"), 'glz', choose=False, programs=nowEPG.get('glz', []))
	LiveChannel('כאן ב', 'bet', 11, os.path.join(imagesDir, "bet.png"), 'kan', choose=False, programs=nowEPG.get('bet', []))
	LiveChannel('כאן גימל', 'gimel', 11, os.path.join(imagesDir, "gimel.png"), 'kan', choose=False, programs=nowEPG.get('gimel', []))
	LiveChannel('כאן תרבות', 'culture', 11, os.path.join(imagesDir, "culture.png"), 'kan', choose=False, programs=nowEPG.get('culture', []))
	LiveChannel('כאן קול המוסיקה', 'music', 11, os.path.join(imagesDir, "music.png"), 'kan', choose=False, programs=nowEPG.get('music', []))
	LiveChannel('כאן מורשת', 'moreshet', 11, os.path.join(imagesDir, "moreshet.png"), 'kan', choose=False, programs=nowEPG.get('moreshet', []))
	LiveChannel('כאן Reka', 'reka', 11, os.path.join(imagesDir, "reka.png"), 'kan', choose=False, programs=nowEPG.get('reka', []))
	LiveChannel('כאן مكان', 'makan', 11, os.path.join(imagesDir, "makan.png"), 'kan', choose=False, programs=nowEPG.get('makan', []))
	LiveChannel('כאן فارسی', 'persian', 11, os.path.join(imagesDir, "persian.png"), 'kan', choose=False, programs=nowEPG.get('persian', []))
	LiveChannel("כאן 80-90", '80-90', 11, os.path.join(imagesDir, "80_90.png"), 'kan', choose=False)
	LiveChannel("כאן קצת אחרת", 'alt', 11, os.path.join(imagesDir, "alt.png"), 'kan', choose=False)
	LiveChannel("כאן קלאסי", 'classic', 11, os.path.join(imagesDir, "classic.png"), 'kan', choose=False)
	LiveChannel("כאן להיטים", 'hits', 11, os.path.join(imagesDir, "hits.png"), 'kan', choose=False)
	LiveChannel("כאן נוסטלגי", 'nos', 11, os.path.join(imagesDir, "nos.png"), 'kan', choose=False)
	LiveChannel("כאן שיא הרגש", 'regesh', 11, os.path.join(imagesDir, "regesh.png"), 'kan', choose=False)
	LiveChannel('כאן ים תיכוני', 'oriental', 11, os.path.join(imagesDir, "oriental.png"), 'kan', choose=False)

if module is None:
	if mode == -1:
		GetCategoriesList()
	elif mode == 1:
		LiveChannels()
	elif mode == 2:
		VODs()
	elif mode == 3:
		Radios()
	elif mode == 4:
		xbmc.executebuiltin("Container.Refresh()")
	elif mode == 5:
		epg.GetEPG(deltaInSec=0)
	if mode == 1 or mode == 3:
		common.SetViewMode('episodes')
else:
	try:
		moduleScript = __import__('resources.lib.{0}'.format(module), fromlist=[module])
		moduleScript.Run(name, url, mode, iconimage, moreData)
	except Exception as ex:
		xbmc.log(str(ex), 3)

xbmcplugin.endOfDirectory(handle)