from Screens.ChoiceBox import ChoiceBox
from Screens.Screen import Screen
from Components.ActionMap import ActionMap, NumberActionMap
from Components.MenuList import MenuList
from Components.Sources.List import List
from Components.FileList import FileList
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from Plugins.Plugin import PluginDescriptor
from Components.Pixmap import Pixmap
from Tools import Notifications
from ServiceReference import ServiceReference
from Components.Button import Button
from Components.Label import Label
from Tools.LoadPixmap import LoadPixmap
from enigma import eTimer
#from enigma import RT_HALIGN_LEFT, eListbox, eListboxPythonMultiContent, gFont
from Tools.Directories import SCOPE_SKIN_IMAGE, resolveFilename
import os
import urllib

Version = "1.00 - 01.10.2017"

plugin_path = "/usr/lib/enigma2/python/Plugins/Extensions/SatLodgeEmu/"

class Emumanager(Screen):
	skin = """<screen name="Emumanager" position="center,center" size="588,450" title="">
		<widget name="list" position="78,64" size="435,150" transparent="1" scrollbarMode="showOnDemand" />
		<!-- ePixmap position="0,0" zPosition="-2" size="584,453" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/SatLodgeEmu/images/out.png" transparent="1" alphatest="on" /-->
		<!--eLabel position="70,100" zPosition="-1" size="100,69" backgroundColor="#222222" /-->
		<widget name="info" position="108,166" size="392,229" font="Regular;18" foregroundColor="white" transparent="1" halign="left" valign="center" />
		<eLabel position="10,400" zPosition="1" size="140,40" backgroundColor="red" />
		<eLabel position="150,400" zPosition="1" size="140,40" backgroundColor="green" />
		<eLabel position="290,400" zPosition="1" size="140,40" backgroundColor="blue" />
		<widget name="key_red" position="10,400" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="#25062748" shadowOffset="-2,-2" />
		<widget name="key_green" position="150,400" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="#25062748" shadowOffset="-2,-2" />
		<widget name="key_blue" position="290,400" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1" shadowColor="#25062748" shadowOffset="-2,-2" />
		<widget name="version" position="440,402" size="145,22" zPosition="1" font="Regular;12" transparent="1" />
		</screen>"""

	def __init__(self, session, args=0):
		self.session = session
		Screen.__init__(self, session)
		self.skinName = "Emumanager"
		self.index = 0
		self.sclist = []
		self.namelist = []
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
		{
			"ok": self.action,
			"cancel": self.close,
			"green": self.action,
			"red": self.close,
			"yellow": self.stop
		}, -1)
		self["key_green"] = Label(_("Start/Restart"))
		self["key_red"] = Label(_("Exit"))
		self["key_yellow"] = Label(_("Stop"))
		self["key_blue"] = Label("")
		try:
			from Plugins.Extensions.SatLodgeDownload.SatLodgeDownload import SatLodgeDownload
			self["actionspowerdownload"] = ActionMap(["ColorActions"],
			{
				"blue": self.callSatLodgeDownload,
			}, -1)
			self["key_blue"].setText(_("SatLodgeDownload"))
		except:
			pass
		try:
			from Plugins.Extensions.OscamStatus.plugin import OscamStatus
			self["actionsoscamstatus"] = ActionMap(["InfobarEPGActions"],
			{
				"showEventInfo": self.callOscamStatus
			}, -1)
		except:
			pass
		self["version"] = Label(_("V. %s" % Version))
		self.lastCam = self.readCurrent()
		self.softcamlist = []
		self["info"] = Label()
		self["list"] = MenuList(self.softcamlist)
		self.readScripts()
		title = _("Sat-Lodge Emu Manager")
		self.setTitle(title)
		self["pixmap"] = Pixmap()
		self.ecmTimer = eTimer()
		self.ecmTimer_conn = self.ecmTimer.timeout.connect(self.ecm) 
		#self.ecm()
		self.onShown.append(self.ecm)
		self.onHide.append(self.stopEcmTimer)

	def stopEcmTimer(self):
		self.ecmTimer.stop()

	def callSatLodgeDownload(self):
		from Plugins.Extensions.SatLodgeDownload.SatLodgeDownload import SatLodgeDownload
		self.session.open(SatLodgeDownload)

	def callOscamStatus(self):
		from Plugins.Extensions.OscamStatus.plugin import OscamStatus
		self.session.open(OscamStatus)

	def getLastIndex(self):
		a = 0
		if len(self.namelist) > 0:
			for x in self.namelist:
				if x == self.lastCam:
					return a
				else:
					a+=1
		else:
			return -1
		return -1

	def action(self):
		self.session.nav.playService(None)
		last = self.getLastIndex()
		var = self["list"].getSelectionIndex()
		if last > -1:
			if last == var:
				self.cmd1 = "/usr/camscript/" + self.sclist[var] + " cam_res &"
				os.system(self.cmd1)
				os.system("sleep 4")
			else:
				self.cmd1 = "/usr/camscript/" + self.sclist[last] + " cam_down &"
				os.system(self.cmd1)
				os.system("sleep 4")
				self.cmd1 = "/usr/camscript/" + self.sclist[var] + " cam_up &"
				os.system(self.cmd1)
		else:
			try:
				self.cmd1 = "/usr/camscript/" + self.sclist[var] + " cam_up &"
				os.system(self.cmd1)
				os.system("sleep 4")
			except:
				#self.close()
				pass

		if last != var:
			try:
				self.lastCam = self.softcamlist[var]
				self.writeFile()
			except:
				#self.close()
				pass
		self.readScripts()
		self.session.nav.playService(self.oldService)
		#self.close()

	def writeFile(self):
		if not self.lastCam is None:
			clist = open("/etc/clist.list", "w")
			clist.write(self.lastCam)
			clist.close()

		stcam = open("/etc/startcam.sh", "w")
		stcam.write("#!/bin/sh\n" + self.cmd1)
		stcam.close()
		self.cmd2 = "chmod 755 /etc/startcam.sh &"
		os.system(self.cmd2)

	def stop(self):
		self.session.nav.playService(None)
		last = self.getLastIndex()

		if last > -1:
			self.cmd1 = "/usr/camscript/" + self.sclist[last] + " cam_down &"
			os.system(self.cmd1)
		else:
			return

		self.lastCam = "no"
		self.writeFile()
		os.system("sleep 4")
		self.readScripts()
		self["info"].setText("")
		self.session.nav.playService(self.oldService)

	def readScripts(self):
		self.index = 0
		scriptliste = []
		pliste = []
		path = "/usr/camscript/"
		for root, dirs, files in os.walk(path):
			for name in files:
				scriptliste.append(name)

		self.sclist = scriptliste

		i = len(self.softcamlist)

		del self.softcamlist[0:i]

		for lines in scriptliste:
			dat = path + lines 
			sfile = open(dat, "r")
			for line in sfile:
				if line[0:3] == "OSD":
					nam = line[5:len(line)-2]
					print "We are in Emumanager readScripts 2 nam = ", nam
					if not self.lastCam is None:
						if nam == self.lastCam:
							self.softcamlist.append(nam + "\tActive")
						else:
							self.softcamlist.append(nam)
						self.index += 1
					else:
						self.softcamlist.append(nam)
						self.index += 1

					pliste.append(nam)

			sfile.close()
			self["list"].setList(self.softcamlist)
			self.namelist = pliste

	def readCurrent(self):
		try:
			clist = open("/etc/clist.list", "r")
		except:
			return None

		if not clist is None:
			for line in clist:
				lastcam = line
			clist.close()
		return lastcam

	def ecm(self):

		ecmf = ""

		if os.path.isfile("/tmp/ecm.info")is True:
			#myfile = file(r"/tmp/ecm.info")
			myfile = open("/tmp/ecm.info", "r")
			ecmf = ""
			for line in myfile.readlines():
				print line
				ecmf = ecmf + line

			myfile.close()
			self["info"].setText(ecmf)

		else:
			self["info"].setText(ecmf)

		self.ecmTimer.start(5000, True)
		return

	def autocam(self):
		current = None
		try:
			clist = open("/etc/clist.list", "r")
			print "found list"
		except:
			return None

		if not clist is None:
			for line in clist:
				current = line
			clist.close()

		print "current =", current

		if os.path.isfile("/etc/autocam.txt")is False:
			alist = open("/etc/autocam.txt", "w")
			alist.close()
		self.cleanauto()
		alist = open("/etc/autocam.txt", "a")
		alist.write(self.oldService.toString() + "\n")
		last = self.getLastIndex()
		alist.write(current + "\n")
		alist.close()
		self.session.openWithCallback(self.callback, MessageBox, _("Autocam assigned to the current channel."), type=1, timeout=10)

	def cleanauto(self):
		delemu = "no"
		if os.path.isfile("/etc/autocam.txt")is False:
			return
		myfile = open("/etc/autocam.txt", "r")
		myfile2 = open("/etc/autocam2.txt", "w")
		icount = 0
		for line in myfile.readlines():
			print "We are in Emumanager line, self.oldService.toString() =", line, self.oldService.toString()
			if line[:-1] == self.oldService.toString():
				delemu = "yes"
				icount = icount+1
				continue
			if delemu == "yes":
				delemu = "no"
				icount = icount+1
				continue

			myfile2.write(line)
			icount = icount+1
		myfile.close() 
		myfile2.close() 
		os.system("rm /etc/autocam.txt")
		os.system("cp /etc/autocam2.txt /etc/autocam.txt")

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

def startConfig(session, **kwargs):
	session.open(Emumanager)

def mainmenu(menuid):
	if menuid != "setup":
		return []
	return [(_("Sat-Lodge Emu Manager"), startConfig, "softcam", None)]

def autostart(reason, session=None, **kwargs):
	"called with reason=1 to during shutdown, with reason=0 at startup?"
	print "[Softcam] Started"
	if reason == 0:
		try:
			os.system("mv /usr/bin/dccamd /usr/bin/dccamdOrig &")
			#os.system("ln -sf /usr/bin /var/bin")
			#os.system("ln -sf /usr/keys /var/keys")
			#os.system("ln -sf /usr/scce /var/scce")
			#os.system("ln -sf /usr/camscript /var/camscript")
			os.system("sleep 2")
			os.system("/etc/startcam.sh &")
		except:
			pass
	else:
		pass

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

def StartSetup(menuid):
	if menuid == "mainmenu":
		return [(_("Sat-Lodge Emu Manager"), main, "softcam", 44)]
	else:
		return []

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

def Plugins(**kwargs):
	return [
			#PluginDescriptor(
			#name=_("Sat-Lodge Emu Manager"), 
			#where=PluginDescriptor.WHERE_MENU, fnc=mainmenu),
			PluginDescriptor(
			name=_("Sat-Lodge Emu Manager"),
			description=_("SatLodgeEmu."),
			where=PluginDescriptor.WHERE_AUTOSTART, fnc=autostart),
			PluginDescriptor(
			name=_("Sat-Lodge Emu Manager"),
			description=_("SatLodgeEmu."),
			where=PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)]
