# -*- coding: utf-8 -*-
import xbmc, xbmcaddon
import os, time, datetime
import resources.lib.common as common

AddonID = 'plugin.video.idanplus'
Addon = xbmcaddon.Addon(AddonID)
module = 'epg'
profileDir = xbmc.translatePath(Addon.getAddonInfo("profile")).decode("utf-8")
if not os.path.exists(profileDir):
	os.makedirs(profileDir)
epgFile = os.path.join(profileDir, 'epg.json')
epgURL = 'http://bit.ly/fishenzonzip'

now = int(time.time())

def ShowChannelEPG(channel, name='', iconimage='', provider='auto', days=2):
	common.addDir('------- [B][COLOR {0}]{1}[/COLOR][/B] -------'.format(Addon.getSetting("chColor"), name), name, 99, iconimage, isFolder=False)
	day = ""
	epg = GetEPG()
	programs = epg[channel]
	for program in programs:
		if now >= program['end']:
			continue
		startdate = datetime.datetime.fromtimestamp(program["start"]).strftime('%d/%m/%y')
		if startdate != day:
			day = startdate
			dayS = '[COLOR {0}][B]{1}:[/B][/COLOR]'.format(Addon.getSetting("nprColor"), day)
			common.addDir(dayS, 'epg', 99, iconimage, {"Title": dayS}, module=module, isFolder=False)
		start_time = datetime.datetime.fromtimestamp(program["start"]).strftime('%H:%M')
		end_time = datetime.datetime.fromtimestamp(program["end"]).strftime('%H:%M')
		programName = "[COLOR {0}][{1}-{2}][/COLOR] [COLOR {3}][B]{4}[/B][/COLOR]".format(Addon.getSetting("timesColor"), start_time, end_time, Addon.getSetting("prColor"), program["name"].strip().encode('utf-8'))
		description = program["description"].strip().encode('utf-8')
		common.addDir(programName, 'epg', 99, iconimage, {"Title": programName, "Plot": description}, module=module, isFolder=False)

def GetNowEPG():
	epg = GetEPG()
	for channel in list(epg.keys()):
		programs = []
		programsCount = len(epg[channel])
		for i in range(programsCount):
			start = epg[channel][i]["start"]
			end = epg[channel][i]["end"]
			if now >= end:
				continue
			if i+1 < programsCount: 
				programs = epg[channel][i:i+2]
				break
			else:
				programs = epg[channel][i:i+1]
				break
		epg[channel] = programs
	return epg

def GetEPG(deltaInSec=86400):
	if common.isFileOld(epgFile, deltaInSec=deltaInSec):
		try:
			data = common.OpenURL(epgURL)
			zFile = os.path.join(profileDir, 'epg.zip')
			with open(zFile, 'wb') as f:
				f.write(data)
			xbmc.executebuiltin("XBMC.Extract({0}, {1})".format(zFile, profileDir), True)
			try:
				os.remove(zFile)
			except:
				pass
		except Exception as ex:
			xbmc.log("{0}".format(ex), 3)
	return common.ReadList(epgFile)

def Run(name, url, mode, iconimage='', moreData=''):
	if mode == 2:
		days = 2
		provider = 'auto'
		if moreData != '':
			params = moreData.split(';')
			for param in params:
				prm = param.split('=')
				if prm[0] == 'provider':
					provider = prm[1]
				elif prm[0] == 'days':
					days = prm[1]
		ShowChannelEPG(url, name, iconimage, provider, days)
	common.SetViewMode('episodes')