# -*- coding: utf-8 -*-
from gLocale import _
from gTools import cleanexit, pathExists

from enigma import eConsoleAppContainer, eTimer
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.ScrollLabel import ScrollLabel

class ShowFileList(Screen):
	def __init__(self, session, file=None, textlist=None, selectlast=True, cmdlist=None):

		self.__file = file
		self.__textlist = textlist
		self.__container = None
		self.__selectlast = selectlast
		self.__cmdlist = cmdlist
		self.__run = 0
		self.__cleanLabel = True

		Screen.__init__(self, session)
		self.skinName = ["ShowFileList-XD","ShowFileList-HD"]
		
		self["text"] = ScrollLabel(_("Please wait..."))

		self["actions"] = ActionMap(["gActions"],
		{
			"exit": self.Exit,
			"up": self["text"].pageUp,
			"left": self["text"].pageUp,
			"down": self["text"].pageDown,
			"right": self["text"].pageDown
		}, -1)

		if cmdlist==None:
			self.ListTimer = eTimer()
			self.ListTimer_conn = self.ListTimer.timeout.connect(self.__filllist)
			self.ListTimer.start(300,True)
		elif len(cmdlist):
			self.__container = eConsoleAppContainer()
			self.__container_appClosed_conn = self.__container.appClosed.connect(self.__runFinished)
			self.__container_dataAvail_conn = self.__container.dataAvail.connect(self.__dataAvail)
			self.onLayoutFinish.append(self.__startRun)
			self.setTitle(_("Console"))
			
	def Exit(self):
		if self.__container is not None:
			del self.__container
		self.close()
		cleanexit(__name__)

	def __filllist(self):
		str = ""
		if self.__textlist is not None:
			for x in self.__textlist:
				str += x+"\n"
		elif self.__file is not None and pathExists(self.__file):
			file = open(self.__file, 'r')
			lines = file.readlines()
			file.close()
			for x in lines:
				str += x
		
		self["text"].setText(str)
		if self.__selectlast:
			self["text"].lastPage()
			
	def __startRun(self):
		if self.__container.execute(self.__cmdlist[self.__run]):
			self.__runFinished(-1)
			
	def __dataAvail(self, str):
		if self.__cleanLabel:
			self.__cleanLabel=False
			self["text"].setText(str)
		else:
			self["text"].setText(self["text"].getText() + str)
		
	def __runFinished(self, retval):
		self.__run += 1
		if self.__run != len(self.__cmdlist):
			if self.__container.execute(self.__cmdlist[self.__run]):
				self.runFinished(-1)
		else:
			str = self["text"].getText()
			str += "\n" + _("Execution finished.");
			self["text"].setText(str)
			if self.__selectlast:
				self["text"].lastPage()
