from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.ActionMap import ActionMap
from Components.Button import Button
from Components.config import config, getConfigListEntry, NoSave, ConfigSelection, ConfigText, ConfigIP, ConfigInteger, ConfigPassword, ConfigYesNo
from Components.ConfigList import ConfigListScreen
from Components.Harddisk import harddiskmanager
from Components.Label import Label
from Components.MenuList import MenuList
from Components.Pixmap import Pixmap
from Components.ProgressBar import ProgressBar
from Components.Sources.List import List
from Components.Sources.StaticText import StaticText
from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN, SCOPE_CURRENT_PLUGIN, SCOPE_SKIN
from Tools.LoadPixmap import LoadPixmap
from enigma import eEnv, eListboxPythonMultiContent, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_VALIGN_CENTER
from os import path, listdir
import xml.dom.minidom as mdom

try:
	from Plugins.Extensions.OscamStatus.plugin import	client, ClientDataScreen, DownloadXMLScreen, elapsedTime, LogDataList, LogDataScreen, OscamDataScreen, \
														OscamRestartScreen, OscamStatus, ReaderDataScreen, ReaderlistScreen, ReaderServiceDataScreen, \
														ReaderstatsScreen, StatusDataScreen, UserstatsScreen, TIMERTICK, VERSION
	from Plugins.Extensions.OscamStatus.OscamStatusSetup import	globalsConfigScreen, oscamServer, OscamServerEntryConfigScreen, OscamServerEntryList, \
																OscamServerEntriesListConfigScreen, readCFG, EXTMENU, LASTSERVER, USEECM, USEPICONS
	print "[PowerMetrixFHD] 001 -OK-- OscamStatus"
except:
	print "[PowerMetrixFHD] 001 -NOK- OscamStatus"

global picons
picons = None

PICONOSCAMPATH_DEFAULT = eEnv.resolve("${datadir}/enigma2/picon_oscam")

def getMountpointsOscam():
	mountpoints = [(PICONOSCAMPATH_DEFAULT + "/", PICONOSCAMPATH_DEFAULT)]
	for p in harddiskmanager.getConfiguredStorageDevices():
		mountpoints.append((p.mountpoint + "/picon_oscam/", p.mountpoint + "/picon_oscam"))
		print "[OscamStatusPatch] Oscam picons path:", p.mountpoint + "/picon_oscam"
	return mountpoints

config.plugins.OscamStatus.PiconOscamPath = ConfigSelection(default = PICONOSCAMPATH_DEFAULT + "/", choices = getMountpointsOscam())
PICONOSCAMPATH = config.plugins.OscamStatus.PiconOscamPath

#######################################################################################################################################################

class piconLoader:
	def __init__(self, Path):
		self.picons = {}
		if path.exists(Path):
			self.Path = Path
			for fname in listdir(self.Path):
				items = fname.rsplit(".", 1)
				self.picons[items[0]] = fname
				print "[OscamStatusPatch] Found picon: %s" % items[0]
			if len(self.picons) == 0:
				print "[OscamStatusPatch] ERROR: no picons found!"
				self.hasLoaded = True
			else:
				print "[OscamStatusPatch] %d picons found..." % len(self.picons)
				self.hasLoaded = True
		else:
			print "[OscamStatusPatch] ERROR: wrong picons path!"
			self.hasLoaded = False

	def getPicon(self, servicename):
		if servicename == "":
			return None
		fname = self.picons.get(servicename.lower().replace(" ", ""), "n/a")
		if fname != "n/a":
			piconpath = self.Path + "/" + fname
			return LoadPixmap(cached=True, path=piconpath)
		else:
			return LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/OscamStatus/icons/unknown.png"))

#######################################################################################################################################################

def OscamStatus__init__(self, session):
	self.session = session
	Screen.__init__(self, session)
	list = []
	list.append((_("Show connected clients"), "clients"))
	list.append((_("Show all clients"), "allClients"))
	list.append((_("Show connected readers"), "readers"))
	list.append((_("Show all readers"), "allReaders"))
	list.append((_("Show logfile"), "log"))
	list.append((_("Server info"), "info"))
	list.append((_("Server restart/shutdown"), "restart"))
	list.append((_("Server setup"), "setup"))
	self["title"] = StaticText("Oscam status " + VERSION)
	self["menu"] = List(list)
	self["actions"] = ActionMap(["OkCancelActions", "DirectionActions", "MenuActions"],
	{
		"ok": self.action,
		"cancel": self.close,
		"menu": self.globalsDlg
	}, -1)
	oscamServers = readCFG()
	index = LASTSERVER.value
	if index+1 > len(oscamServers):
		index = 0
	self.SetupCB(oscamServers[index])
	self.piconsLoaded = False
	if USEPICONS.value:
		self.loadPicons()

def OscamStatusloadPicons(self):
	global picons
	print "[OscamStatusPatch] Oscam picons path:", PICONOSCAMPATH.value
	picons = piconLoader(PICONOSCAMPATH.value)
	if picons.hasLoaded:
		self.piconsLoaded = True
		print "[OscamStatusPatch] Picons activated..."
	else:
		self.piconsLoaded = False
		print "[OscamStatusPatch] Picons deactivated..."
		USEPICONS.value = False

def OscamStatusaction(self):
	returnValue = self["menu"].getCurrent()[1]
	if returnValue is not None:
		if returnValue is "clients":
			self.session.open(StatusDataScreen, "clients", "status", self.oServer)
		elif returnValue is "allClients":
			self.session.open(UserstatsScreen, "userstats", self.oServer)
		elif returnValue is "readers":
			self.session.open(StatusDataScreen, "readers", "status", self.oServer)
		elif returnValue is "allReaders":
			self.session.open(ReaderlistScreen, "readerlist", self.oServer)
		elif returnValue is "log":
			self.session.open(LogDataScreen, "status&appendlog=1", self.oServer)
		elif returnValue is "info":
			self.session.open(OscamDataScreen, "status", self.oServer)
		elif returnValue is "setup":
			self.session.openWithCallback(self.SetupCB, OscamServerEntriesListConfigScreen)
		elif returnValue is "restart":
			self.session.open(OscamRestartScreen, "status", self.oServer)

def OscamStatusSetupCB(self, entry):
	if entry:
		self.oServer = entry
		self["title"].setText("Oscam status " + VERSION + " @" + self.oServer.serverName)

def OscamStatusglobalsDlg(self):
	self.oldpath = PICONOSCAMPATH.value
	self.session.openWithCallback(self.globalsCB, globalsConfigScreen)

def OscamStatusglobalsCB(self):
	if USEPICONS.value:
		if not self.piconsLoaded or self.oldpath != PICONOSCAMPATH.value:
			self.loadPicons()

#######################################################################################################################################################

def globalsConfigScreen__init__(self, session):
	self.session = session
	Screen.__init__(self, session)

	list = []
	list.append(getConfigListEntry(_("Show Plugin in Extensions Menu"), EXTMENU))
	list.append(getConfigListEntry(_("ECM Time in \"connected\" Dialog"), USEECM))
	list.append(getConfigListEntry(_("Server address always in IP Format"), config.plugins.OscamStatus.useIP))
	list.append(getConfigListEntry(_("Use Picons"), USEPICONS))
	PICONOSCAMPATH.setChoices(getMountpointsOscam(), default = PICONOSCAMPATH_DEFAULT + "/")
	list.append(getConfigListEntry(_("Picons Path"), PICONOSCAMPATH))
	ConfigListScreen.__init__(self, list, session=session)

	self["title"] = StaticText(_("Oscam status globals setup"))
	self["key_red"] = StaticText(_("Return"))
	self["key_green"] = StaticText(_("Save"))
	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"red": self.Exit,
		"green": self.Save,
		"cancel": self.Exit
	}, -1)

#######################################################################################################################################################

def OscamServerEntryList__init__(self, list, enableWrapAround = True):
	MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
	self.l.setFont(0, gFont("Regular", 34))
	self.pic0 = LoadPixmap(cached=True, path=resolveFilename(SCOPE_SKIN, "skin_default/icons/lock_off.png"))
	self.pic1 = LoadPixmap(cached=True, path=resolveFilename(SCOPE_SKIN, "skin_default/icons/lock_on.png"))

def OscamServerEntryListmakeList(self, index):
	self.list = []
	oscamServers = readCFG()
	for cnt, i in enumerate(oscamServers):
		res = [i]
		if cnt == index:
			res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 6, 0, 54, 54, self.pic1))
		else:
			res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 6, 0, 54, 54, self.pic0))
		res.append((eListboxPythonMultiContent.TYPE_TEXT,  66, 0, 280, 54, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, i.serverName))
		res.append((eListboxPythonMultiContent.TYPE_TEXT, 366, 0, 469, 54, 0, RT_HALIGN_RIGHT|RT_VALIGN_CENTER, i.serverIP))
		res.append((eListboxPythonMultiContent.TYPE_TEXT, 855, 0, 120, 54, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, i.serverPort))
		if i.useSSL:
			txt = "ON"
		else:
			txt = "OFF"
		res.append((eListboxPythonMultiContent.TYPE_TEXT, 995, 0, 100, 54, 0, RT_HALIGN_RIGHT|RT_VALIGN_CENTER, txt))
		self.list.append(res)
	self.l.setList(self.list)
	self.moveToIndex(index)

#######################################################################################################################################################

def OscamServerEntriesListConfigScreen__init__(self, session):
	self.session = session
	Screen.__init__(self, session)

	self["list"] = OscamServerEntryList([])
	self["list"].makeList(LASTSERVER.value)

	self["title"] = StaticText(_("Oscam servers"))
	self["Nametext"] = Label(_("Server name"))
	self["IPtext"] = Label(_("IP"))
	self["Porttext"] = Label(_("Port"))
	self["SSLtext"] = Label(_("SSL"))
	self["ButtonGreentext"] = StaticText(_("New"))
	self["ButtonYellowtext"] = StaticText(_("Edit"))
	self["ButtonBluetext"] = StaticText(_("Delete"))

	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"green": self.keyNew,
		"yellow": self.keyEdit,
		"blue": self.keyDelete,
		"ok": self.keyOk,
		"cancel": self.keyClose
	}, -1)

#######################################################################################################################################################

def OscamServerEntryConfigScreen__init__(self, session, entry, index):
	self.session = session
	Screen.__init__(self, session)

	if entry == None:
		entry = oscamServer()
	self.index = index

	serverIP = self.isIPaddress(entry.serverIP)
	if serverIP and config.plugins.OscamStatus.useIP.value:
		self.isIP = True
	else:
		self.isIP = False

	serverPort = int(entry.serverPort)

	self.serverNameConfigEntry = NoSave(ConfigText(default=entry.serverName, fixed_size=False, visible_width=20))
	if self.isIP:
		self.serverIPConfigEntry = NoSave(ConfigIP(default=serverIP, auto_jump=True))
	else:
		self.serverIPConfigEntry = NoSave(ConfigText(default=entry.serverIP, fixed_size=False, visible_width=20))
		self.serverIPConfigEntry.setUseableChars(u'1234567890aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ.-_')
	self.portConfigEntry = NoSave(ConfigInteger(default=serverPort, limits=(0,65536)))
	self.usernameConfigEntry = NoSave(ConfigText(default=entry.username, fixed_size=False, visible_width=20))
	self.passwordConfigEntry = NoSave(ConfigPassword(default=entry.password, fixed_size=False))
	self.useSSLConfigEntry = NoSave(ConfigYesNo(entry.useSSL))

	ConfigListScreen.__init__(self, [], session=session)
	self.createSetup()

	self["title"] = StaticText(_("Oscam server setup"))
	self["key_red"] = StaticText(_("Return"))
	self["key_green"] = StaticText(_("Save"))
	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"red": self.Close,
		"green": self.Save,
		"cancel": self.Close
	}, -1)

#######################################################################################################################################################

def ReaderServiceDataScreen__init__(self, session, r):
	def compare(a, b):
		return cmp(a[0], b[0]) or cmp(a[1], b[1])

	self.session = session
	Screen.__init__(self, session)

	tmp = []
	for c in r[0].cards:
		for p in c.providers:
			tmp.append((c.caid, p.provid, p.service, c.system, c.number))

	self["title"] = StaticText(str(len(tmp)) + " services @" + r[0].label + " (" + r[0].hostaddress + ")")

	self["data"] = List(sorted(tmp, compare))
	self["actions"] = ActionMap(["OkCancelActions"],
	{
		"cancel": self.close
	}, -1)

#######################################################################################################################################################

def ClientDataScreen__init__(self, session, type, oServer, data):
	self.session = session
	self.type = type
	self.oServer = oServer
	Screen.__init__(self, session)

	auEntrys = {"1": "ACTIVE", "0": "OFF", "-1": "ON"}

	self["title"] = StaticText("")
	self["KeyYellow"] = Pixmap()
	self["KeyYellow"].hide()
	self["KeyYellowtext"] = StaticText("")

	if type == "clients":
		self["title"].setText("Client " + data.name + "@" + oServer.serverName)
	else:
		self["title"].setText("Reader " + data.name + "@" + oServer.serverName)
		if data.protocol.startswith("cccam"):
			self["KeyYellow"].show()
			self["KeyYellowtext"].setText("Show reader data")

	self.ecmhistory = data.ecmhistory.split(",")
	if self.ecmhistory[0] == "":
		self.ecmhistory[0] = "0"
	if len(self.ecmhistory) < 20:
		for x in range(20 - len(self.ecmhistory)):
			self.ecmhistory.append("0")

	maxh = 0.0
	for i in range(20):
		self["progress%d" % i] = ProgressBar()
		self.ecmhistory[i] = float(self.ecmhistory[i])
		if self.ecmhistory[i] > maxh:
			maxh = self.ecmhistory[i]
	if maxh < 1000.0:
		self.base = 1000.0
	elif maxh < 2000.0:
		self.base = 2000.0
	elif maxh < 3000.0:
		self.base = 3000.0
	elif maxh < 4000.0:
		self.base = 4000.0
	elif maxh < 5000.0:
		self.base = 5000.0
	else:
		self.base = 9999.0

	self.name = data.name
	self.protocol = data.protocol
	self["lprotocol"] = StaticText("Protocol:")
	self["protocol"] = StaticText(data.protocol or "n/a")
	self["lprotocolext"] = StaticText("Protocolext:")
	self["protocolext"] = StaticText(data.protocolext or "n/a")
	self["lau"] = StaticText("AU:")
	self["au"] = StaticText(auEntrys[data.au])
	self["lcaid"] = StaticText("CAID:")
	self["caid"] = StaticText(data.caid or "n/a")
	self["lsrvid"] = StaticText("SRVID:")
	self["srvid"] = StaticText(data.srvid or "n/a")
	self["lecmtime"] = StaticText("ECM time:")
	self["ecmtime"] = StaticText(data.ecmtime or "n/a")
	self["lecmhistory"] = StaticText("ECM history:")
	self["historymax"] = StaticText(str(int(self.base)))
	self["historymin"] = StaticText("0")
	self["lanswered"] = StaticText("Answered:")
	self["answered"] = StaticText(data.answered or "n/a")
	self["lservice"] = StaticText("Service:")
	self["service"] = StaticText(data.service or "n/a")
	self["llogin"] = StaticText("Login:")
	self["login"] = StaticText(data.login and data.login.replace("T", " ").replace("+", " +") or "n/a")
	self["lonline"] = StaticText("Online:")
	self["online"] = StaticText(elapsedTime(data.online, "%02dd %02dh %02dm %02ds", True) or "n/a")
	self["lidle"] = StaticText("Idle:")
	self["idle"] = StaticText(elapsedTime(data.idle, "%02d:%02d:%02d") or "n/a")
	self["lip"] = StaticText("IP:")
	self["ip"] = StaticText(data.ip or "n/a")
	self["lport"] = StaticText("Port:")
	self["port"] = StaticText(data.port or "n/a")
	self["lconnection"] = StaticText("Connection:")
	self["connection"] = StaticText(data.connection or "n/a")

	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"yellow": self.yellowPressed,
		"cancel": self.Close
	}, -1)
	self.onExecBegin.append(self.setProgress)

#######################################################################################################################################################

def OscamDataScreen__init__(self, session, part, oServer):
	self.oServer = oServer
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer, False)

	self["lversion"] = StaticText("Version:")
	self["version"] = StaticText("")
	self["lrevision"] = StaticText("Revision:")
	self["revision"] = StaticText("")
	self["lstarttime"] = StaticText("Start time:")
	self["starttime"] = StaticText("")
	self["luptime"] = StaticText("Uptime:")
	self["uptime"] = StaticText("")
	self["lreadonly"] = StaticText("Read-only:")
	self[ "readonly"] = StaticText("")

	self["actions"] = ActionMap(["OkCancelActions"],
	{
		"cancel": self.Close
	}, -1)

def OscamDataScreendlAction(self):
	dom = mdom.parseString(self.data)
	d = self.parseXML(dom)

	readonlyEntrys = {"1": "YES", "0": "NO"}

	self.setTitle("Oscam server" + " @" + self.oServer.serverName)
	self["version"].setText(d.version or "n/a")
	self["revision"].setText(d.revision or "n/a")
	self["starttime"].setText(d.starttime and d.starttime.replace("T", " ").replace("+", " +") or "n/a")
	self["uptime"].setText(elapsedTime(d.uptime, "%d days %d hours %d minutes %d seconds", True) or "n/a")
	self["readonly"].setText(readonlyEntrys[d.readonly])

#######################################################################################################################################################

def OscamRestartScreen__init__(self, session, part, oServer):
	self.oServer = oServer
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer, False)

	self["lversion"] = StaticText("Version:")
	self["version"] = StaticText("")
	self["lrevision"] = StaticText("Revision:")
	self["revision"] = StaticText("")
	self["lstarttime"] = StaticText("Start time:")
	self["starttime"] = StaticText("")
	self["luptime"] = StaticText("Uptime:")
	self["uptime"] = StaticText("")
	self["lreadonly"] = StaticText("Read-only:")
	self["readonly"] = StaticText("")

	self["ButtonYellow"] = Pixmap()
	self["ButtonYellowtext"] = Button(_("Restart Oscam"))
	self["ButtonBlue"] = Pixmap()
	self["ButtonBluetext"] = Button(_("Shutdown Oscam"))

	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"yellow": self.yellowPressed,
		"blue": self.bluePressed,
		"cancel": self.Close
	}, -1)
	self.canRestart = False

def OscamRestartScreendlAction(self):
	if self.newurl:
		self.close(0)
	dom = mdom.parseString(self.data)
	d = self.parseXML(dom)

	readonlyEntrys = {"1": "YES", "0": "NO"}

	self.setTitle("Oscam server" + " @" + self.oServer.serverName)
	self["version"].setText(d.version or "n/a")
	self["revision"].setText(d.revision or "n/a")
	self["starttime"].setText(d.starttime and d.starttime.replace("T", " ").replace("+", " +") or "n/a")
	self["uptime"].setText(elapsedTime(d.uptime, "%d days %d hours %d minutes %d seconds", True) or "n/a")
	self[ "readonly"].setText(readonlyEntrys[d.readonly])

	if not self.canRestart:
		msg = _("You can\'t shutdown/restart this Oscam:")
		if not int(d.revision) > 4716:
			msg += _("\n- Oscam revision is %s (min. 4717 needed)") % d.revision
		if int(d.readonly):
			msg += _("\n- webif is read-only!")
		self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 10, windowTitle = "Oscam status")
		self.close(1)

def OscamRestartScreenyellowPressed(self):
	if self.download:
		return
	self.mode = "restart"
	self.mbox(_("Really restart Oscam@%s?") % self.oServer.serverName)

def OscamRestartScreenbluePressed(self):
	if self.download:
		return
	self.mode = "shutdown"
	self.mbox(_("Really shutdown Oscam@%s?") % self.oServer.serverName)

def OscamRestartScreenmbox(self, txt):
	self.session.openWithCallback(self.mboxCB, MessageBox, txt, default = False, windowTitle = "Oscam status")

#######################################################################################################################################################

def ReaderDataScreen__init__(self, session, part, oServer):
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer, False)

	self["data"] = List([])
	self["KeyYellow"] = Pixmap()
	self["KeyYellowtext"] = Label("Show reader service data")
	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"yellow": self.yellowPressed,
		"cancel": self.Close
	}, -1)

def ReaderDataScreendlAction(self):
	dom = mdom.parseString(self.data)
	r = self.parseXML(dom)

	list = []
	self.setTitle(r[0].totalcards + " cards @" + r[0].label + " (" + r[0].hostaddress + ")")
	for c in r[0].cards:
		p = c.providers
		if len(p) >= 6:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			p[0].number, p[0].service, p[1].number, p[1].service, p[2].number, p[2].service, p[3].number, p[3].service, \
			p[4].number, p[4].service, p[5].number, p[5].service))
		elif len(p) == 5:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			p[0].number, p[0].service, p[1].number, p[1].service, p[2].number, p[2].service, p[3].number, p[3].service, \
			p[4].number, p[4].service, " ", " "))
		elif len(p) == 4:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			p[0].number, p[0].service, p[1].number, p[1].service, p[2].number, p[2].service, p[3].number, p[3].service, " ", " ", " ", " "))
		elif len(p) == 3:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			p[0].number, p[0].service, p[1].number, p[1].service, p[2].number, p[2].service, " ", " ", " ", " ", " ", " "))
		elif len(p) == 2:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			p[0].number, p[0].service, p[1].number, p[1].service, " ", " ", " ", " ", " ", " ", " ", " "))
		elif len(p) == 1:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			p[0].number, p[0].service, " ", " ", " ", " ", " ", " ", " ", " ", " ", " "))
		elif len(p) == 0:
			list.append((c.number, c.caid, c.system, "reshare = " + c.reshare, "hops = " + c.hop, \
			" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "))
	self["data"].setList(list)
	self.r = r

#######################################################################################################################################################

def LogDataScreen__init__(self, session, part, oServer):
	self.oServer = oServer
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer)

	self.onPause = False
	self["data"] = LogDataList([], 30)
	self["KeyYellow"] = Pixmap()
	self["KeyYellowtext"] = Label("Pause log")
	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"yellow": self.yellowPressed,
		"cancel": self.Close
	}, -1)

def LogDataScreendlAction(self):
	dom = mdom.parseString(self.data)
	log = self.parseXML(dom)

	self.setTitle("Logfile @" + self.oServer.serverName)
	list = []
	for line in log.splitlines():
		if "rejected" in line or "invalid" in line: c = "0xff2222" # red
		elif "written" in line: c = "0xff8c00" # orange
		elif " r " in line: c = "0xffd700" # yellow
		elif " p " in line: c = "0xadff2f" # green
		else: c = "0xffffff" # white
		item = [line]
		split = line.split("(", 1)
		txt = split[0].strip()
		if len(split) > 1 and split[1]:
			split = split[1].split(")", 1)
			txt = txt + " (" + split[0].strip() + ") " + (len(split) > 1 and split[1].strip() or "")
		item.append((eListboxPythonMultiContent.TYPE_TEXT, 10, 0, 1830, 40, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, txt, int(c, 16)))
		list.append(item)
	self["data"].setList(list)
	self["data"].selectionEnabled(0)
	x = len(list)
	if x:
		self["data"].moveToIndex(x-1)

def LogDataScreenyellowPressed(self):
	if self.onPause:
		self.downloadXML()
		self.timer.start(TIMERTICK)
		self["KeyYellowtext"].setText("Pause log")
		self.onPause = False
	else:
		self.timer.stop()
		self["KeyYellowtext"].setText("Unpause log")
		self.onPause = True

#######################################################################################################################################################

def ReaderlistScreen__init__(self, session, part, oServer):
	self.oServer = oServer
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer)

	self["label0"] = StaticText(_("Reader"))
	self["label1"] = StaticText(_("Protocol"))
	self["label2"] = StaticText(_("Type"))

	self["data"] = List(list)
	self["ButtonRed"] = Pixmap()
	self["ButtonRedtext"] = Button(_("Disable reader"))
	self["ButtonGreen"] = Pixmap()
	self["ButtonGreentext"] = Button(_("Enable reader"))

	self["ButtonRed"].hide()
	self["ButtonRedtext"].hide()
	self["ButtonGreen"].hide()
	self["ButtonGreentext"].hide()

	self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"],
	{
		"up": self.upPressed,
		"down": self.downPressed,
		"left": self.leftPressed,
		"right": self.rightPressed,
		"red": self.redPressed,
		"green": self.greenPressed,
		"cancel": self.Close
	}, -1)

	self.icondis = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
								"skin_default/icons/disabled.png"))
	self.iconena = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
								"skin_default/icons/enabled.png"))

	self.isReadonly = True
	self.index = 0

def ReaderlistScreensetList(self):
	list = []
	self.setTitle("All readers @" + self.oServer.serverName)
	for index, r in enumerate(self.readers):
		if r.enabled == "1":
			list.append((self.iconena, r.label, r.protocol, r.type, r.enabled, index))
		else:
			list.append((self.icondis, r.label, r.protocol, r.type, r.enabled, index))
	self["data"].setList(list)
	if self.index < len(list):
		self["data"].setIndex(self.index)

	if self.isReadonly:
		self["ButtonRed"].hide()
		self["ButtonRedtext"].hide()
		self["ButtonGreen"].hide()
		self["ButtonGreentext"].hide()
	self.setupButtons()

#######################################################################################################################################################

def ReaderstatsScreen__init__(self, session, reader, part, oServer):
	self.oServer = oServer
	self.reader = reader
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer)

	self["label0"] = StaticText(_("Count"))
	self["label1"] = StaticText(_("Channelname"))
	self["label2"] = StaticText(_("caid:srvid"))
	self["label3"] = StaticText(_("Status"))
	self["label4"] = StaticText(_("Last-Time"))
	self["label5"] = StaticText(_("Avg-Time"))
	self["lEMMerror"]   = StaticText("EMM error\nUK / G / S / UQ")
	self["lEMMwritten"] = StaticText("EMM written\nUK / G / S / UQ")
	self["lEMMskipped"] = StaticText("EMM skipped\nUK / G / S / UQ")
	self["lEMMblocked"] = StaticText("EMM blocked\nUK / G / S / UQ")
	self["EMMerror"]   = Label("")
	self["EMMwritten"] = Label("")
	self["EMMskipped"] = Label("")
	self["EMMblocked"] = Label("")
	self["data"] = List(list)
	self["actions"] = ActionMap(["OkCancelActions"],
	{
		"cancel": self.Close
	}, -1)

def ReaderstatsScreensetList(self):
	def compare(a, b):
		return cmp(int(b[0]), int(a[0]))

	EMMerror = EMMwritten = EMMskipped = EMMblocked = ""
	for r in ["error", "written", "skipped", "blocked"]:
		for t in ["unknown", "global", "shared", "unique"]:
			for e in self.emms:
				if r == e.result and t == e.type:
					if r == "error":
						EMMerror += e.val + " / "
					if r == "written":
						EMMwritten += e.val + " / "
					if r == "skipped":
						EMMskipped += e.val + " / "
					if r == "blocked":
						EMMblocked += e.val + " / "
	self["EMMerror"].setText(EMMerror[:-3])
	self["EMMwritten"].setText(EMMwritten[:-3])
	self["EMMskipped"].setText(EMMskipped[:-3])
	self["EMMblocked"].setText(EMMblocked[:-3])

	list = []
	self.setTitle("Status reader " + self.reader + "@" + self.oServer.serverName)
	for e in self.ecms:
		channelname = e.channelname
		if USEPICONS.value:
			picon = picons.getPicon(channelname)
			list.append((e.val, channelname, e.caid + ":" + e.srvid, e.rcs, e.lasttime, e.avgtime, picon, channelname, ""))
		else:
			list.append((e.val, channelname, e.caid + ":" + e.srvid, e.rcs, e.lasttime, e.avgtime, None, "", channelname))

	list.sort(compare)
	self["data"].setList(list)
	self["data"].setIndex(self.oldIndex)

#######################################################################################################################################################

def UserstatsScreen__init__(self, session, part, oServer):
	self.oServer = oServer
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer)

	self["label0"] = StaticText(_("Client (IP if online)"))
	self["label1"] = StaticText(_("Time on channel"))
	self["label2"] = StaticText(_("Status"))
	self["label3"] = StaticText(_("Protocol"))

	self["data"] = List(list, enableWrapAround=True)
	self["ButtonRed"] = Pixmap()
	self["ButtonRedtext"] = Button(_("Disable client"))
	self["ButtonGreen"] = Pixmap()
	self["ButtonGreentext"] = Button(_("Enable client"))

	self["ButtonRed"].hide()
	self["ButtonRedtext"].hide()
	self["ButtonGreen"].hide()
	self["ButtonGreentext"].hide()

	self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"],
	{
		"up": self.upPressed,
		"down": self.downPressed,
		"left": self.leftPressed,
		"right": self.rightPressed,
		"red": self.redPressed,
		"green": self.greenPressed,
		"cancel": self.Close
	}, -1)

	self.icondis = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
								"skin_default/icons/disabled.png"))
	self.iconena = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
								"skin_default/icons/enabled.png"))

	self.isReadonly = True
	self.index = 0

def UserstatsScreensetList(self):
	list = []
	self.setTitle("All clients @" + self.oServer.serverName)
	for index, u in enumerate(self.users):
		name = u.name
		if u.ip:
			name = u.name + " (" + u.ip + ")"
		if u.timeonchannel != "n/a":
			u.timeonchannel = elapsedTime(u.timeonchannel, "%02d:%02d:%02d")
		if "disabled" in u.status:
			list.append((self.icondis, u.name, u.timeonchannel, u.status, u.protocol, index, name))
		else:
			list.append((self.iconena, u.name, u.timeonchannel, u.status, u.protocol, index, name))
	self["data"].setList(list)
	if self.index < len(list):
		self["data"].setIndex(self.index)

	if self.isReadonly:
		self["ButtonRed"].hide()
		self["ButtonRedtext"].hide()
		self["ButtonGreen"].hide()
		self["ButtonGreentext"].hide()
	self.setupButtons()

#######################################################################################################################################################

def StatusDataScreen__init__(self, session, type, part, oServer):
	self.oServer = oServer
	self.session = session

	Screen.__init__(self, session)
	DownloadXMLScreen.__init__(self, session, part, oServer)

	self.type = type
	self["data"] = List([])

	if self.type == "clients":
		self.skinName = "StatusDataScreenClients"
		self["label0"] = StaticText(_("User (protocol)"))
		self["label1"] = StaticText(_("Reader"))
		self["label2"] = StaticText(_("AU"))
		if USEECM.value:
			self["label3"] = StaticText(_("ECM time"))
		else:
			self["label3"] = StaticText(_("Idle time"))
		self["label4"] = StaticText(_("Last channel"))
		self["ButtonYellow"] = Pixmap()
		self["ButtonYellowtext"] = Button(_("Show client info"))
		self["ButtonBlue"] = Pixmap()
		self["ButtonBluetext"] = Button(_("Hide idle clients"))
	else:
		self.skinName = "StatusDataScreenReaders"
		self["label0"] = StaticText(_("Reader"))
		self["label1"] = StaticText(_("Status"))
		self["label2"] = StaticText(_("AU"))
		if USEECM.value:
			self["label3"] = StaticText(_("ECM time"))
		else:
			self["label3"] = StaticText(_("Idle time"))
		self["label4"] = StaticText(_("Protocol"))
		self["label5"] = StaticText(_("Last channel"))
		self["ButtonYellow"] = Pixmap()
		self["ButtonYellowtext"] = Button(_("Show reader info"))
		self["ButtonBlue"] = Pixmap()
		self["ButtonBluetext"] = Button(_("Show reader status"))

	self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
	{
		"yellow": self.yellowPressed,
		"blue": self.bluePressed,
		"cancel": self.Close
	}, -1)

	auRed = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
						"skin_default/buttons/button_red.png"))
	auGreen = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
						"skin_default/buttons/button_green.png"))
	auYellow = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN,
						"skin_default/buttons/button_yellow.png"))

	self.auEntrys = {"1": auGreen, "0": auRed, "-1": auYellow}
	self.hideIdle = False

def StatusDataScreensetList(self):
	dlist = []
	if self.type == "clients":
		self.setTitle("Connected clients @" + self.oServer.serverName)
		for index, c in enumerate(self.status):
			if c.type == "c":
				if USEECM.value:
					idle = c.ecmtime
				else:
					idle = elapsedTime(c.idle, "%02d:%02d:%02d")
				service = ((c.service != "n/a" and c.service != "unknown") and c.service or " ").rsplit("[", 1)[0].strip()
				protocol = c.protocol and c.protocol or "n/a"
				user = c.name + " (" + protocol + ")"
				if self.hideIdle:
					if c.answered != "":
						if USEPICONS.value:
							picon = picons.getPicon(service)
							dlist.append((c.name, c.answered, self.auEntrys[c.au], idle, c.service, index, picon, service, "", user))
						else:
							dlist.append((c.name, c.answered, self.auEntrys[c.au], idle, c.service, index, None, "", service, user))
				else:
					if USEPICONS.value:
						picon = picons.getPicon(service)
						dlist.append((c.name, c.answered, self.auEntrys[c.au], idle, c.service, index, picon, service, "", user))
					else:
						dlist.append((c.name, c.answered, self.auEntrys[c.au], idle, c.service, index, None, "", service, user))
	elif self.type == "readers":
		self.setTitle("Connected readers @" + self.oServer.serverName)
		for index, c in enumerate(self.status):
			if c.type == "r" or c.type == "p":
				if USEECM.value:
					idle = c.ecmtime
				else:
					idle = elapsedTime(c.idle, "%02d:%02d:%02d")
				service = ((c.service != "n/a" and c.service != "unknown") and c.service or " ").rsplit("[", 1)[0].strip()
				protocol = c.protocol.rsplit("(", 1)[0].strip()
				if USEPICONS.value:
					picon = picons.getPicon(service)
					dlist.append((c.name, c.connection, self.auEntrys[c.au], idle, protocol, index, picon, service, ""))
				else:
					dlist.append((c.name, c.connection, self.auEntrys[c.au], idle, protocol, index, None, "", service))

	self["data"].setList(dlist)
	self["data"].setIndex(self.oldIndex)

def StatusDataScreenbluePressed(self):
	if self.download:
		return
	if self.type == "readers" and self["data"].count():
		reader = self["data"].getCurrent()[0]
		part = "readerstats&label=" + reader
		self.session.openWithCallback(self.backCB, ReaderstatsScreen, reader, part, self.oServer)
		return
	if self.hideIdle:
		self["ButtonBluetext"].setText(_("Hide idle clients"))
	else:
		self["ButtonBluetext"].setText(_("Show idle clients"))
	self.hideIdle = not self.hideIdle
	self.setList()

#######################################################################################################################################################

def doOscamStatusChange():
	try:
		OscamStatus.loadPicons = OscamStatusloadPicons
		OscamStatus.action = OscamStatusaction
		OscamStatus.SetupCB = OscamStatusSetupCB
		OscamStatus.globalsCB = OscamStatusglobalsCB
		OscamStatus.globalsDlg = OscamStatusglobalsDlg
		OscamStatus.__init__ = OscamStatus__init__
		OscamServerEntryList.__init__ = OscamServerEntryList__init__
		OscamServerEntryList.makeList = OscamServerEntryListmakeList
		OscamServerEntriesListConfigScreen.__init__ = OscamServerEntriesListConfigScreen__init__
		OscamServerEntryConfigScreen.__init__ = OscamServerEntryConfigScreen__init__
		globalsConfigScreen.__init__ = globalsConfigScreen__init__
		ReaderServiceDataScreen.__init__ = ReaderServiceDataScreen__init__
		ClientDataScreen.__init__ = ClientDataScreen__init__
		OscamDataScreen.dlAction = OscamDataScreendlAction
		OscamDataScreen.__init__ = OscamDataScreen__init__
		OscamRestartScreen.mbox = OscamRestartScreenmbox
		OscamRestartScreen.yellowPressed = OscamRestartScreenyellowPressed
		OscamRestartScreen.bluePressed = OscamRestartScreenbluePressed
		OscamRestartScreen.dlAction = OscamRestartScreendlAction
		OscamRestartScreen.__init__ = OscamRestartScreen__init__
		ReaderDataScreen.dlAction = ReaderDataScreendlAction
		ReaderDataScreen.__init__ = ReaderDataScreen__init__
		LogDataScreen.yellowPressed = LogDataScreenyellowPressed
		LogDataScreen.dlAction = LogDataScreendlAction
		LogDataScreen.__init__ = LogDataScreen__init__
		ReaderlistScreen.setList = ReaderlistScreensetList
		ReaderlistScreen.__init__ = ReaderlistScreen__init__
		ReaderstatsScreen.setList = ReaderstatsScreensetList
		ReaderstatsScreen.__init__ = ReaderstatsScreen__init__
		UserstatsScreen.setList = UserstatsScreensetList
		UserstatsScreen.__init__ = UserstatsScreen__init__
		StatusDataScreen.bluePressed = StatusDataScreenbluePressed
		StatusDataScreen.setList = StatusDataScreensetList
		StatusDataScreen.__init__ = StatusDataScreen__init__
		print "[PowerMetrixFHD] 001 -OK-- OscamStatus"
	except:
		print "[PowerMetrixFHD] 001 -NOK- OscamStatus"
