from __future__ import print_function
from __future__ import absolute_import
from Components.ActionMap import ActionMap, HelpableActionMap
from Components.ConfigList import ConfigListScreen
from Components.config import config, ConfigSelection, getConfigListEntry, ConfigSubsection, ConfigClock, ConfigInteger,  ConfigOnOff, ConfigYesNo
from Components.Label import Label
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaBlend
from Components.Pixmap import Pixmap
from Components.ScrollLabel import ScrollLabel
from Components.Sources.List import List
from Plugins.Plugin import PluginDescriptor
from Plugins.SystemPlugins.SoftwareManager.plugin import UpdatePlugin
from Screens.ChoiceBox import ChoiceBox
from Screens.Screen import Screen
from Screens.HelpMenu import HelpableScreen
from Screens.MessageBox import MessageBox
from Tools import Notifications
from Tools.Directories import fileExists
from Tools.LoadPixmap import LoadPixmap
from calendar import timegm
from enigma import gFont, eConsoleAppContainer
from .merlintimer import merlintimer
from .merlinupdater import merlinupdater
from merlin.emerlin import eMerlin
from time import time, strftime, localtime, mktime, strptime
from twisted.web.client import getPage, downloadPage
from . import _

import json
import re
import xml.etree.cElementTree

updateSummary = re.compile('([0-9]+) upgraded, ([0-9]+) newly installed, ([0-9]+) to remove and ([0-9]+) not upgraded\.')
changelog = re.compile('<pre>\n(.*?)</pre><ul>\n', flags=re.DOTALL)
gitlog = re.compile('&lt;pre style=&#39;white-space:pre-wrap;width:81ex&#39;&gt;(.*?)&lt;/pre&gt;\n', flags=re.DOTALL)

now = localtime()
begin = mktime((now.tm_year, now.tm_mon, now.tm_mday, 22, 0, 0, now.tm_wday, now.tm_yday, now.tm_isdst))


config.plugins.merlinupdatechecker = ConfigSubsection()
config.plugins.merlinupdatechecker.active = ConfigOnOff(default = False) 
config.plugins.merlinupdatechecker.checkon = ConfigSelection([("127", _("daily")),("0", _("Monday")), ("1", _("Tuesday")), ("2", _("Wednesday")), ("3", _("Thursday")), ("4", _("Friday")), ("5", _("Saturday")), ("6", _("Sunday"))], default="5")
config.plugins.merlinupdatechecker.time = ConfigClock(default=int(begin))
config.plugins.merlinupdatechecker.wakeuptime = ConfigInteger(default=-1)
config.plugins.merlinupdatechecker.lastscantime = ConfigInteger(default=0)
config.plugins.merlinupdatechecker.wakeupforcheck = ConfigYesNo(default=False)

try:
	Notifications.notificationQueue.registerDomain("MerlinUpdateChecker", _("Merlin Update Checker"), deferred_callable = True)
except Exception as e:
	print("[MerlinUpdateChecker] - Error registering Notification-Domain: ", e)

def main(session, **kwargs):
	session.open(MerlinUpdateChecker)
	
def setTimer(reason, **kwargs):
	if reason == 0 and "session" in kwargs:
		session = kwargs["session"]
		merlintimer.session = session
		merlinupdater.session = session
		
		if config.plugins.merlinupdatechecker.active.value:
			# todo: when box is started shortly before the timer it goes into standby. not good.
			if  config.misc.prev_wakeup_time.value == config.plugins.merlinupdatechecker.wakeuptime.value:
				print("[MerlinUpdateChecker] - started Dreambox based on timer")
				from Screens.Standby import Standby, inStandby
				if not inStandby:
					from Tools import Notifications
					Notifications.AddNotificationWithID("Standby", Standby)
			merlinupdater.setTimer()

# this only sets the wake up timer for the next check when stopping enigma2		
def getNextWakeUp():
	if not config.plugins.merlinupdatechecker.active.value or not config.plugins.merlinupdatechecker.wakeupforcheck.value:
		print("[MerlinUpdateChecker] - not activated")
		setWakeUpTimeInConfig(-1)
		return -1
	else:
		print("[MerlinUpdateChecker] - activated")
		
		now = localtime()

		begin = int(mktime( (now.tm_year, now.tm_mon, now.tm_mday,
		config.plugins.merlinupdatechecker.time.value[0],
		config.plugins.merlinupdatechecker.time.value[1],
		0, now.tm_wday, now.tm_yday, now.tm_isdst )
		))
		
		if int(config.plugins.merlinupdatechecker.checkon.value) == now.tm_wday or config.plugins.merlinupdatechecker.checkon.value == "127":
			print("[MerlinUpdateChecker] - weekday matches config")
			print("[MerlinUpdateChecker] - start time is ", begin)
			print("[MerlinUpdateChecker] - today is ", now.tm_wday)
			print("[MerlinUpdateChecker] - update checker runs ", config.plugins.merlinupdatechecker.checkon.value)
			if begin > time():
				print("[MerlinUpdateChecker] - start time is in the future")
				setWakeUpTimeInConfig(begin)
				return begin
			else:
				print("[MerlinUpdateChecker] - we're passed the start time")
				if config.plugins.merlinupdatechecker.checkon.value == "127":
					# let's try our luck the next day	
					print("[MerlinUpdateChecker] -  let's check again tomorrow - daily")
					setWakeUpTimeInConfig(begin)
					return begin+86400
				else:
					# next time is in a week				
					print("[MerlinUpdateChecker] - let's check again in one week")
					setWakeUpTimeInConfig(begin)
					return begin+(7*86400)
		else:
			print("[MerlinUpdateChecker] - weekday does not match config")
			delta = now.tm_wday - int(config.plugins.merlinupdatechecker.checkon.value)
			if delta < 0:
				remdays = delta*-1
			else:
				remdays = 7 - delta
			setWakeUpTimeInConfig(begin)
			return begin+(remdays*86400)

def setWakeUpTimeInConfig(wakeUpTime):
	config.plugins.merlinupdatechecker.wakeuptime.value = wakeUpTime
	config.plugins.merlinupdatechecker.save()

def addMerlinUpdateCheckerToMenu(menuid):
	if menuid != "merlin":
		return []
	return [(_("Merlin Update Checker"), showMerlinUpdateCheckerConfig, "merlinupdatechecker", 70)]
	
def showMerlinUpdateCheckerConfig(session, **kwargs):
	session.open(ConfigurationMenu)
	
def openMerlinUpdateChecker(session, args, **kwargs):
	session.open(MerlinUpdateChecker)
	
def Plugins(**kwargs):
	return [
		#PluginDescriptor(name="Merlin Update Checker", description="Plugin to check for any update on the feed", where=[PluginDescriptor.WHERE_PLUGINMENU], fnc=main),
		PluginDescriptor(where=[PluginDescriptor.WHERE_SESSIONSTART,PluginDescriptor.WHERE_AUTOSTART], fnc=setTimer, wakeupfnc=getNextWakeUp),
		PluginDescriptor(where=[PluginDescriptor.WHERE_MENU], fnc=addMerlinUpdateCheckerToMenu),
		PluginDescriptor(name="Merlin Update Checker", where=[PluginDescriptor.WHERE_SOFTWAREMANAGER], fnc={"SoftwareSupported":openMerlinUpdateChecker,"menuEntryName":_("Merlin Update Checker"),"menuEntryDescription":_("Plugin to check if there are updates available for Merlin")})
		]
	
class MerlinUpdateChecker(Screen, HelpableScreen):
	skin = """
		<screen name="MerlinUpdateChecker" position="center,80" size="600,300" title="Merlin Update Checker" >
			<widget font="Regular;18" name="state" position="50,0" size="500,240" zPosition="3" halign="center" valign="center" /> 
			<widget source="list" render="Listbox" position="50,0" size="500,240" scrollbarMode="showOnDemand" zPosition="1">
				<convert type="TemplatedMultiContent">
					{"templates": {
						"default": (60,
							[
								MultiContentEntryText(pos=(5,5), size=(50,50), font=1, text=1, flags=RT_HALIGN_CENTER|RT_VALIGN_CENTER, backcolor=0xa90000, backcolor_sel=0xa90000, color=0xffffff, color_sel=0xffffff),   
								MultiContentEntryText(pos=(70,0), size=(430,60), font=0, text=0, flags=RT_VALIGN_CENTER),   								                                        
							])
						},      
						"fonts": [gFont("Regular",25),gFont("Regular",30)],
					}
				</convert>
			</widget> 
			<widget font="Regular;18" name="red" position="0,260" size="150,25" foregroundColor="red" /> 
			<widget font="Regular;18" name="green" position="150,260" size="150,25" foregroundColor="green" />
			<widget font="Regular;18" name="yellow" position="300,260" size="150,25" foregroundColor="yellow" />
			<widget font="Regular;18" name="blue" position="450,260" size="150,25" foregroundColor="blue" />									
		</screen>
		"""
	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
		{
			"ok":		(self.executeCommand, _("Check for updates")),
			"cancel":	(self.close, _("Close plugin")),
		}, -1)
		
		self["ColorActions"] = HelpableActionMap(self, "ColorActions",
		{
			"red":			(self.showPackages, _("Show packages")),
			"green":		(self.startUpgrade, _("Start update")),
			"yellow":		(self.getEnigma2Log, _("Get enigma2 changelog")),
			"blue":			(self.getGithubRepos, _("Get changelog for a selected github repo")),
		}, -1)
		
		self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions",
		{
			"info":			(self.showPackages, _("Show packages")),
		}, -1)
		
		self["MenuActions"] = HelpableActionMap(self, "MenuActions",
		{
			"menu":			(self.showConfigMenu, _("Show config menu")),
		}, -1)
		
		self.list = []
		self["list"] = List(self.list)
		self["list"].setBuildFunc(self.buildEntry)
		self["list"].setSelectionEnabled(False)
		self["red"] = Label(_("Show packages"))
		self["green"] = Label(_("Start update"))
		self["yellow"] = Label(_("enigma2 changelog"))
		self["blue"] = Label(_("github changelog"))
		self["state"] = Label(_("Checking for updates..."))
		self["state"].show()
		
		self.container = eConsoleAppContainer()
		self.appClosed_conn = self.container.appClosed.connect(self.commandFinished)
		self.dataAvail_conn = self.container.dataAvail.connect(self.readData)
		self.stdErrAvail_conn = self.container.stderrAvail.connect(self.getError)
	
		self.cmdList = ["apt-get update", "apt-get -s dist-upgrade"]

		# todo: move to own class to support re-use	
		self.remainingData = ""
		self.currentCommand = 0
		self.updatablePackagesList = []
		self.heldPackagesList = []
		self.newPackagesList = []
		self.removePackagesList = []
		self.autoremovePackagesList = []
		self.errorList = []
		self.totalUpgrade = 0
		self.totalNew = 0
		self.totalHeld = 0
		self.totalRem = 0
		self.currentList = ""
		self.index = 0
		
		self.onLayoutFinish.append(self.executeCommand)

	def showConfigMenu(self):
		self.session.open(ConfigurationMenu)		

	def buildEntry(self, labeltext, counttext):
		return [ labeltext, counttext ]

	def showPackages(self):
		category = self["list"].getCurrent()[0]
		if category == _("Upgradable"):
			self.session.open(MerlinPackageInfo, self.updatablePackagesList)
		elif category == _("New"):
			self.session.open(MerlinPackageInfo, self.newPackagesList)
		elif category == _("Removable"):
			self.session.open(MerlinPackageInfo, self.removePackagesList)
		elif category == _("Kept back"):
			self.session.open(MerlinPackageInfo, self.heldPackagesList)

	def startUpgrade(self):
		self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to update your Dreambox?")+"\n"+_("\nAfter pressing OK, please wait!"))
	
	def runUpgrade(self, result):
		if result:
			self.session.openWithCallback(self.closePlugin, UpdatePlugin)
			
	def closePlugin(self):
		self.close()

	def getGithubRepos(self):
		getPage("https://api.github.com/orgs/opendreambox/repos", method='GET').addCallback(self.prepareGithubRepoList).addErrback(self.printError)
		
	def prepareGithubRepoList(self, jsonstring):
		repoDict = json.loads(jsonstring)
		repoDetailList = []
		
		for repo in repoDict:
			repoId = repo.get('id', None)
			repoName = repo.get('name', None)
			
			if repoName is not None:
				repoDetailList.append((str(repoName), str(repoId)))
				
		if len(repoDetailList)>0:
			self.session.openWithCallback(self.getGithubLog, ChoiceBox, title = _("Select repository"), list = repoDetailList)

	def getGithubLog(self, repo):
		if repo:
			self.session.open(MerlinGithubLogViewer, repo[0])
		
	def getEnigma2Log(self):
		getPage("http://git.opendreambox.org/?p=enigma2.git;a=atom", method='GET').addCallback(self.readXML).addErrback(self.printError)
		
	def readXML(self, data):
		
		changelogList = changelog.findall(data)
		if len(changelogList)>0:
			self.session.open(MerlinLogViewer,changelogList)
				
	def printError(self, error):
		print(error)
	
	def getError(self, error):
		self.errorList.append(str(error))
		print(error)
		
	def readData(self, data):
		if self.currentCommand > 0:
			data = self.remainingData + data
			lines = data.split("\n")
			
			if len(lines[-1]):
				self.remainingData = lines[-1]
				lines = lines[0:-1]
			else:
				self.remainingData = ""
				
			i = 0
			
			for i in range(len(lines)):
				# it's a package
				if lines[i].startswith("  "):
					if self.currentList == "newPackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":						
								self.newPackagesList.append((line.strip(),))
					elif self.currentList == "heldPackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":						
								self.heldPackagesList.append((line.strip(),))
					elif self.currentList == "removePackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":
								self.removePackagesList.append((line.strip(),))
					elif self.currentList == "autoRemovePackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":
								self.autoremovePackagesList.append((line.strip(),))
					elif self.currentList == "updatablePackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":
								self.updatablePackagesList.append((line.strip(),))
					else:
						print("not a supported list")
				else:
					# it's a lead line
					if lines[i].startswith("The following NEW packages will be installed:"):
						self.currentList = "newPackages"
					elif lines[i].startswith("The following packages have been kept back:"):
						self.currentList = "heldPackages"
					elif lines[i].startswith("The following packages will be REMOVED:"):
						self.currentList = "removePackages"
					elif lines[i].startswith("The following packages were automatically installed and are no longer required:"):
						self.currentList = "autoRemovePackages"
					elif lines[i].startswith("The following packages will be upgraded:"):
						self.currentList = "updatablePackages"
					else:
						updateSummaryCheck = updateSummary.match(lines[i])
						if updateSummaryCheck is not None:
							if len(updateSummaryCheck.groups()) == 4:
								self.totalUpgrade = updateSummaryCheck.groups()[0]
								self.totalNew = updateSummaryCheck.groups()[1]
								self.totalRem = updateSummaryCheck.groups()[2]
								self.totalHeld = updateSummaryCheck.groups()[3]						
		
	def commandFinished(self, retVal):
		if retVal == 0:
			if self.currentCommand == 0:
				# command is apt-get update
				self.currentCommand = 1
				self.executeCommand()
			else:
				print("up", self.totalUpgrade)
				print("new", self.totalNew)
				print("rem", self.totalRem)
				print("held", self.totalHeld)
				print("we can end now")
				print("new", len(self.newPackagesList))
				print("held", len(self.heldPackagesList))
				print("up", len(self.updatablePackagesList))
				
				self["state"].hide()
				
				self.list = [(_("Upgradable"), self.totalUpgrade), (_("New"), self.totalNew), (_("Removable"), self.totalRem), (_("Kept back"), self.totalHeld) ]
				
				self["list"].setList(self.list)
				
	def executeCommand(self):
		self.container.execute(self.cmdList[self.currentCommand])
				
class MerlinPackageInfo(Screen, HelpableScreen):
	skin = """
		<screen name="MerlinPackageInfo" position="center,50" size="500,500" title="Merlin Package Info" >
			<widget source="list" render="Listbox" position="0,0" size="500,480" scrollbarMode="showOnDemand" zPosition="1">
				<convert type="TemplatedMultiContent">
					{"templates": {
						"default": (30,
							[
								MultiContentEntryText(pos=(0,0), size=(500,30), font=0, text=0, flags=RT_VALIGN_CENTER),   								                                        
							])
						},      
						"fonts": [gFont("Regular",20)],
					}
				</convert>
			</widget> 
		</screen>
		"""
	def __init__(self, session, packageList, args = None):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
		{
			"cancel":	(self.close, _("Close plugin")),
		}, -1)
		
		"""self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions",
		{
			"info":			(self.showPackages, _("Show packages")),
		}, -1)"""
		
		self.list = packageList 
		print(self.list)
		self["list"] = List(self.list)
		self["list"].setBuildFunc(self.buildEntry)	
	
	def buildEntry(self, package):
		print(package)
		return [package]

class MerlinGithubLogViewer(Screen, HelpableScreen):
	skin = """
		<screen name="MerlinGithubLogViewer" position="center,50" size="890,560" title="Merlin Log Viewer" >
			<widget source="list" render="Listbox" position="0,0" size="420,500" scrollbarMode="showOnDemand" zPosition="1">
				<convert type="TemplatedMultiContent">
					{"templates": {
						"default": (100,
							[
								MultiContentEntryText(pos=(0,0), size=(400,50), font=0, text=2, flags=RT_WRAP),
								MultiContentEntryText(pos=(60,50), size=(180,25), font=1, text=0),
								MultiContentEntryText(pos=(240,50), size=(160,25), font=1, text=1, flags=RT_HALIGN_RIGHT),
								MultiContentEntryPixmapAlphaBlend(pos=(0,50), size=(50,50), png=4)
							]),
						
						},
						      
						"fonts": [gFont("Regular",18), gFont("Regular",15)],
					}
				</convert>
			</widget>
			<widget font="Regular;18" name="message" position="430,0" size="420,500" /> 
			<widget font="Regular;18" name="info" position="270,530" size="250,25" />
			<widget font="Regular;18" name="red" position="10,530" size="250,25" foregroundColor="red" />
			
		</screen>
		"""
	def __init__(self, session, repo="", args = None):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
				
		self["WizardActions"] = HelpableActionMap(self, "WizardActions",
		{
			"ok":           (self.toggleList,_("Toggle active list")),
			"back":         (self.close,_("Close screen")),
			"left":         (self.pageUp,_("Page up")),
			"right":        (self.pageDown,_("Page down")),
		}, -1)
		
		self["ColorActions"] = HelpableActionMap(self, "ColorActions",
		{
			"red":			(self.getMoreCommits, _("Get more commits")),
		
		}, -1)
		
		self.list = []
		self.msgList = {}
		self["list"] = List(self.list)
		self["message"] = ScrollLabel()
		self["info"] = Label(_("Press OK to change list"))
		self["red"] = Label(_("Get more commits"))
		self.currentList = "list"
		self.index = 0
		self.page = 1
		self.repo = repo
		
		self.commitList = []
		self.avatarList = []
		self.commitMessageDict = {}
		self.getGithubLog(self.repo, self.page)
		
		self["list"].setBuildFunc(self.buildEntry)
		self["list"].onSelectionChanged.append(self.buildMessageEntry)
		
	def buildMessageEntry(self):
		self["message"].setText(self.msgList.get(self["list"].getCurrent()[3], None))
		
		
	def buildEntry(self, author, date, shortmessage, sha):
		ptr = eMerlin.getInstance().loadImage("/usr/lib/enigma2/python/Plugins/SystemPlugins/MerlinUpdateChecker/avatars/%s" %(author))
		return [author, date, shortmessage, sha, ptr]
	
	def toggleList(self):
		if self.currentList == "list":
			self.currentList = "message"
		else:
			self.currentList = "list"
		
	def pageUp(self):
		if self.currentList == "list":
			self["list"].pageUp()
		else:
			self["message"].pageUp()
	
	def pageDown(self):
		if self.currentList == "list":
			self["list"].pageDown()
		else:
			self["message"].pageDown()
			
	def getMoreCommits(self):
		self.page += 1
		self.getGithubLog(self.repo, self.page)
			
	def getGithubLog(self, repo="enigma2-plugins", page=1):
		if repo:
			getPage("https://api.github.com/repos/opendreambox/%s/commits?page=%d" %(repo, page), method='GET').addCallback(self.updateGithubCommits).addErrback(self.printError)
			
	def updateGithubCommits(self, jsonstring):
		commitDict = json.loads(jsonstring)

		
		for commit in commitDict:
			message = None
			shortmessage = None
			author = None
			date = None
			sha = None
			sha = commit.get("sha", None)
			commitData = commit.get("commit", None)
			if commitData is not None:
				authorData = commitData.get("author", None)
				if authorData is not None:
					author = authorData.get("name", None)
					date = authorData.get("date", None)
				message = commitData.get("message", None)
				shortmessage = message
				if len(message)>67:
					shortmessage = message[:67]+"..."
				if author is not None and date is not None and message is not None:
					tm = strptime(str(date),  "%Y-%m-%dT%H:%M:%SZ")
					epoch = float(timegm(tm))
					dtobj = strftime("%a, %d %b %Y %H:%M:%S", localtime(epoch))

					self.list.append((str(author), dtobj, str(shortmessage), str(sha)))
					self.msgList[str(sha)] = str(message)
					authorInfo = commit.get("author", None)
					if authorInfo is not None:
						avatar = authorInfo.get("avatar_url", None)
						if avatar is not None:
							if not str(avatar) in self.avatarList:
								self.avatarList.append((str(author),str(avatar)))
					
		self.checkAvatarList()
		
	def checkAvatarList(self):
		currentIndex = self.index
		self.index += 1
		if currentIndex == len(self.avatarList):
			if self.page == 1:
				self.buildMessageEntry()

			self["list"].updateList(self.list)
		else:
			if not fileExists("/usr/lib/enigma2/python/Plugins/SystemPlugins/MerlinUpdateChecker/avatars/%s" %(self.avatarList[currentIndex][0])):
				downloadPage(self.avatarList[currentIndex][1], file("/usr/lib/enigma2/python/Plugins/SystemPlugins/MerlinUpdateChecker/avatars/%s" %(self.avatarList[currentIndex][0]),'wb')).addCallback(self.downloadFinished).addErrback(self.printError)
			else:
				self.checkAvatarList()
			
	def downloadFinished(self, result):
		self.checkAvatarList()
								
	def printError(self, error):
		print(error)
				
class MerlinLogViewer(Screen, HelpableScreen):
	skin = """
		<screen name="MerlinLogViewer" position="center,50" size="890,560" title="Merlin Log Viewer" >
			<!--widget source="list" render="Listbox" position="0,0" size="800,500" scrollbarMode="showOnDemand" zPosition="1">
				<convert type="TemplatedMultiContent">
					{"templates": {
						"default": (500,
							[
								MultiContentEntryText(pos=(0,0), size=(500,500), font=0, text=0, flags=RT_WRAP),   								                                        
							])
						},      
						"fonts": [gFont("Regular",20)],
					}
				</convert>
			</widget-->
			<widget font="Regular;30" name="left" position="0,0" size="20,560" valign="center" halign="center" />
			<widget font="Regular;20" name="text" position="20,0" size="850,560" /> 
			<widget font="Regular;30" name="right" position="870,0" size="20,560" valign="center" halign="center" />
		</screen>
		"""
	def __init__(self, session, changelogList, args = None):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
				
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
		{
			"cancel":	(self.close, _("Close screen")),
		}, -1)
		
		self["DirectionActions"] = HelpableActionMap(self, "DirectionActions",
		{
			"up":		(self.pageUp, _("up")),
			"down":		(self.pageDown, _("down")),
			"right":		(self.prevEntry, _("previous")),
			"left":	(self.nextEntry, _("next")),
		}, -1)

		self.changelogList = changelogList
		self["text"] = ScrollLabel()
		self["left"] = Label("<")
		self["left"].hide()
		self["right"] = Label(">")
		self.currentIndex = 0
		
		self.onLayoutFinish.append(self.getLogEntry)

	def pageUp(self):
		self["text"].pageUp()
		
	def pageDown(self):
		self["text"].pageDown()
		
	def prevEntry(self):
		if self.currentIndex < len(self.changelogList)-1:
			self.currentIndex+=1
			self.getLogEntry()
			if self.currentIndex == len(self.changelogList)-1:
				self["right"].hide()
			elif self.currentIndex == 1:
				self["left"].show()
			
	def nextEntry(self):
		if self.currentIndex > 0:
			self.currentIndex-=1
			self.getLogEntry()
			if self.currentIndex == 0:
				self["left"].hide()
			elif self.currentIndex == len(self.changelogList)-2:
				self["right"].show()
		
	def getLogEntry(self):
		if len(self.changelogList):
			self["text"].setText(self.changelogList[self.currentIndex].replace("&quot;","\"").replace("&lt;","<").replace("&gt;",">"))

class ConfigurationMenu(Screen, HelpableScreen, ConfigListScreen):
	skin = """
			<screen position="center,center" size="600,170" title="MerlinUpdateChecker - Config">
				<widget name="config" position="0,0" size="600,130" scrollbarMode="showOnDemand" />
				<widget name="ButtonGreentext" position="20,130" size="350,40" valign="center" halign="left" zPosition="10" font="Regular;18" transparent="1" />
				<widget name="ButtonGreen" pixmap="skin_default/buttons/button_green.png" position="0,140" zPosition="10" size="16,16" transparent="1" alphatest="on" />
			</screen>
		"""	
	
	def __init__(self, session, args=None):
		self.session = session
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
				
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
		{
			"cancel":	(self.close, _("Close plugin")),
			"ok":		(self.saveSelection, _("Save")),
		}, -1)
		
		self["ColorActions"] = HelpableActionMap(self, "ColorActions",
		{
			"green":	(self.saveSelection, _("Save")),
		}, -1)
		
		self["ButtonGreen"] = Pixmap()
		self["ButtonGreentext"] = Label(_("Save settings"))
		
		self.list = []
		
		self.merlinupdatecheckeractive = config.plugins.merlinupdatechecker.active
		
		ConfigListScreen.__init__(self, self.list)
		
		self.createConfig()
		
	def saveSelection(self):
		for x in self["config"].list:
			x[1].save()
		
		merlinupdater.session = self.session	
		merlinupdater.setTimer()
			
		self.close()

	def newConfig(self):
		cur = self["config"].getCurrent()
		if cur and cur[1] == self.merlinupdatecheckeractive:
			self.createConfig("config")
		
	def createConfig(self, configElement=""):
		self.list = []
		self.list.append(getConfigListEntry(_("Activate Merlin Update Checker"), self.merlinupdatecheckeractive))
		#todo: if false set other values to default
		if config.plugins.merlinupdatechecker.active.value:
			self.list.append(getConfigListEntry(_("Check for updates"), config.plugins.merlinupdatechecker.checkon))
			self.list.append(getConfigListEntry(_("Check at"), config.plugins.merlinupdatechecker.time ))
			self.list.append(getConfigListEntry(_("Wake up for check"), config.plugins.merlinupdatechecker.wakeupforcheck))
			
		self["config"].setList(self.list)
		
	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()
		