from __future__ import print_function
from Components.ActionMap import HelpableActionMap, ActionMap
from Components.ConfigList import ConfigListScreen
from Components.config import config, getConfigListEntry
from Components.Label import Label
from Components.Sources.List import List
from Components.Sources.StaticText import StaticText
from Plugins.Plugin import PluginDescriptor
from Screens.HelpMenu import HelpableScreen
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.SkinSettings import SkinSettingsSetup
from Screens.Standby import TryQuitMainloop
from Tools.LoadPixmap import LoadPixmap
from Tools.Directories import resolveFilename, SCOPE_SKIN
from os import walk as os_walk
from os import system as os_system
from os import path as os_path
from os import listdir as os_listdir

CAMPATH = '/usr/bin/cam/'

def isRunning(pname):
	pname = '\t' + pname
	for f in os_listdir('/proc'):
		try:
			cmdline = open(os_path.join('/', 'proc', f, 'status'), 'r')
			txt = cmdline.read()
			cmdline.close()
			if pname in txt:
				return True
		except IOError:
			pass
	return False

def main(session,**kwargs):
    session.open(SysCC)

def Plugins(**kwargs):
    return [PluginDescriptor(name="SysCC", description=_("Systemd Cam Center"),
            where = [PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU ],
            icon="syscc.png", fnc=main)]

class SysCC(Screen):
	skin = """
	<screen position="center,center" size="400,400" title="SysCC" >
		<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/SysCC/buttons.png" position="100,355" size="200,40" alphatest="on" zPosition="5"/>
		<widget source="entries" render="Listbox" position="5,5" size="390,320" scrollbarMode="showOnDemand">
			<convert type="TemplatedMultiContent">
				{"template": [
					MultiContentEntryText(pos = (30, 6), size = (370, 25), font=0, flags = RT_HALIGN_LEFT, text = 0),
					MultiContentEntryPixmapAlphaTest(pos = (5, 9), size = (14, 14), png = 1)
				],
				"fonts": [gFont("Regular", 20)],
				"itemHeight": 32
				}
			</convert>
		</widget>
	</screen>"""

	def __init__(self, session, args = 0):
		self.skin = SysCC.skin
		self.session = session
		Screen.__init__(self, session)

		self["entries"] = List([])
		self["actions"] = ActionMap(["OkCancelActions", "ColorActions","MenuActions"],
		{
			"ok"    : self.green_pressed,
			"cancel": self.close,
			"green" : self.green_pressed,
			"red"   : self.red_pressed,
			"menu"  : self.openSkinSettings,
		}, -1)

		self.icon_start = LoadPixmap(cached=True, path=resolveFilename\
		(SCOPE_SKIN, "Merlin/green.png"))
		self.icon_stop  = LoadPixmap(cached=True, path=resolveFilename\
		(SCOPE_SKIN, "Merlin/red.png"))

		self.camEntries = []
		self.runningCam = None
		for root, dirs, files in os_walk(CAMPATH):
			for name in files:
				self.camEntries.append(name)
				if isRunning(name):
					self.runningCam = name

		self.index = 0
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()

		self["entries"].onSelectionChanged.append(self.updateSummary)
		self.onShown.append(self.genListEntries)

	def genListEntries(self):
		list = []

		for cam in self.camEntries:
			if self.runningCam == cam:
				list.append((cam, self.icon_start)) 
			else:
				list.append((cam, self.icon_stop)) 

		self["entries"].setList(list)
		if len(list):
			self["entries"].setIndex(self.index)

	def green_pressed(self):
		if not len(self.camEntries):
			return

		self.session.nav.playService(None)

		self.index = self["entries"].getIndex()
		cam = self.camEntries[self.index]
		if self.runningCam == cam:
			print('[SysCC] restart:', cam)
			self.handleCam(cam, 'restart')
		else:
			if self.runningCam is not None:
				print('[SysCC] stop :', self.runningCam)
				self.handleCam(self.runningCam, 'stop')
			print('[SysCC] start:', cam)
			self.handleCam(cam, 'start')
			self.runningCam = cam

		self.session.nav.playService(self.oldService)
		self.genListEntries()

	def red_pressed(self):
		if not len(self.camEntries):
			return

		self.session.nav.playService(None)

		self.index = self["entries"].getIndex()
		cam = self.camEntries[self.index]
		if self.runningCam == cam:
			print('[SysCC] stop:', cam)
			self.handleCam(cam, 'stop')
			self.runningCam = None

		self.session.nav.playService(self.oldService)
		self.genListEntries()

	def handleCam(self, cam, state):
		if state == 'start':
			cmd = "systemctl enable %s && systemctl start %s" % (cam, cam)
		elif state == 'stop':
			cmd = "systemctl stop %s && systemctl disable %s" % (cam, cam)
		else:
			cmd = "systemctl restart %s" % cam
		#print '______________', cmd
		print('[SysCC] handleCam returns:', os_system(cmd))

	def createSummary(self):
		return SysCCLCDScreen
		
	def updateSummary(self):
		cam    = " "
		status = " "
		if len(self.camEntries):
			cam = self.camEntries[self["entries"].getIndex()]
			if cam == self.runningCam:
				status = "running"
			else:
				status = "stopped"
		self.summaries.setText(cam,    1)
		self.summaries.setText(status, 2)
		
	def openSkinSettings(self):
		self.session.open(SkinSettingsSetup)


class SysCCLCDScreen(Screen):
	skin = (
	"""<screen name="SysCCLCDScreen" position="0,0" size="132,64" id="1">
		<widget name="plugin" position="4,0" size="132,35" font="Regular;16"/>
		<widget name="listentry" position="4,36" size="132,14" font="Regular;10"/>
		<widget name="status" position="4,49" size="132,14" font="Regular;10"/>
	</screen>""",
	"""<screen name="SysCCLCDScreen" position="0,0" size="96,64" id="2">
		<widget name="plugin" position="0,0" size="96,35" font="Regular;14"/>
		<widget name="listentry" position="0,36" size="96,14" font="Regular;10"/>
		<widget name="status" position="0,49" size="96,14" font="Regular;10"/>
	</screen>""",
	"""<screen name="SysCCLCDScreen" position="0,0" size="400,240" id="3">
		<widget name="plugin" position="0,5" size="400,90" halign="center" font="Regular;70"/>
		<widget name="listentry" position="10,95" size="380,70" font="Regular;60"/>
		<widget name="status" position="10,160" size="380,70" halign="right" font="Regular;60"/>
	</screen>""")
	
	def __init__(self, session, parent):
		Screen.__init__(self, session)
		self["plugin"] = Label("SysCC")
		self["listentry"] = Label(" ")
		self["status"] = Label(" ")

	def setText(self, text, line):
		if line == 1:
			self["listentry"].setText(text)
		if line == 2:
			self["status"].setText(text)

class SkinSettingsSysCC(Screen, HelpableScreen, ConfigListScreen):
	skin = """
		<screen name="SkinSettingsSysCC" position="center,center" size="600,400" title="Skin Settings" >
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" zPosition="0" size="140,40" transparent="1" alphatest="on" />
			<widget render="Label" source="key_red" position="0,0" size="140,40" zPosition="5" valign="center" halign="center" backgroundColor="red" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget render="Label" source="key_green" position="140,0" size="140,40" zPosition="5" valign="center" halign="center" backgroundColor="red" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget render="Label" source="key_yellow" position="280,0" size="140,40" zPosition="5" valign="center" halign="center" backgroundColor="yellow" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget name="config" position="20,50" size="560,330" scrollbarMode="showOnDemand" />
		</screen>"""

	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self.setTitle(_("Skin Settings"))

		self["SetupActions"] = HelpableActionMap(self, "SetupActions",
		{
			"cancel":	(self.close, _("Discard changes and close")),
		}, -2)
		
		self["ColorActions"] = HelpableActionMap(self, "ColorActions",
		{
			"green":	(self.keySave, _("Save settings")),
			"red":		(self.keyCancel, _("Discard changes and close")),
		}, -2)
		
		self["key_blue"] = StaticText("")
		self["key_yellow"] = StaticText("")
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("OK"))

		self.list = []
		ConfigListScreen.__init__(self, self.list, session = session)
		
		self.createConfig()
		config.merlin2.skin_showdecryption.addNotifier(self.createConfig)
		config.merlin2.skin_showfta.addNotifier(self.createConfig)
		config.merlin2.skin_simpledecodeinfo.addNotifier(self.createConfig)

	def createConfig(self,configElement=""):
		self.list = []

		self.list.append(getConfigListEntry(_("Show camd name"), config.merlin2.skin_showcamdname))
		self.list.append(getConfigListEntry(_("Show encryption"), config.merlin2.skin_showencryption))
		self.list.append(getConfigListEntry(_("Show decryption"), config.merlin2.skin_showdecryption))
		if config.merlin2.skin_showdecryption.value:
			self.list.append(getConfigListEntry(_("Show FTA"), config.merlin2.skin_showfta))
			if config.merlin2.skin_showfta.value:
				self.list.append(getConfigListEntry(_("FTA text"), config.merlin2.skin_ftatext))
			self.list.append(getConfigListEntry(_("Simple decodeinfo"), config.merlin2.skin_simpledecodeinfo))
			if not config.merlin2.skin_simpledecodeinfo.value:
				self.list.append(getConfigListEntry(_("Reader / source display"), config.merlin2.skin_readersource))
		else:
			config.merlin2.skin_showfta.value = False
			config.merlin2.skin_simpledecodeinfo.value = False
			
		self["config"].list = self.list
		self["config"].l.setList(self.list)

	def keySave(self):
		for x in self["config"].list:
			x[1].save()
		
		info = self.session.openWithCallback(self.restartGUI,MessageBox,_("Please restart enigma2 for changes to take effect. Restart now?"), MessageBox.TYPE_YESNO)
		info.setTitle(_("Skin Settings"))	
		#self.updateSkin()
	
	def restartGUI(self, answer):
		if answer:
			self.session.open(TryQuitMainloop, 3)


