from Screens.Screen import Screen
from Plugins.Plugin import PluginDescriptor
from Screens.MessageBox import MessageBox
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Sources.List import List
from Components.PluginComponent import plugins
from os import system, path, listdir, rename, popen
from enigma import eConsoleAppContainer
from Tools.Directories import fileExists, SCOPE_PLUGINS, resolveFilename
from enigma import eTimer, eDVBDB

class SatLodgeManualInstall(Screen):
	__module__ = __name__
	skin = """
		<screen position="80,95" size="560,430">
			<widget name="title" position="10,5" size="320,55" font="Regular;28" foregroundColor="#ff2525" backgroundColor="transpBlack" transparent="1"/>
			<widget source="list" render="Listbox" position="14,49" size="900,480" scrollbarMode="showOnDemand">
			<convert type="TemplatedMultiContent">
				{"template": [
						MultiContentEntryText(pos = (60, 0), size = (520, 25), font=0,color=0xCC0000, flags = RT_HALIGN_LEFT|RT_VALIGN_TOP, text = 0), # index 0 is the title
					],
				"fonts": [gFont("Regular", 20),gFont("Regular", 16)],
				"itemHeight": 20
				}
			</convert>
		</widget>
			<widget name="conn" position="0,360" size="540,50" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" />
			<widget name="key_red" position="0,510" size="280,20" zPosition="1" font="Regular;22" valign="center" foregroundColor="#0064c7" backgroundColor="#9f1313" transparent="1" />
			<widget name="key_yellow" position="280,510" size="280,20" zPosition="1" font="Regular;22" valign="center" foregroundColor="#bab329" backgroundColor="#9f1313" transparent="1" />
		</screen>"""

	def __init__(self, session):
		Screen.__init__(self, session)
		self.list = []
		self['list'] = List(self.list)
		self['conn'] = Label('')
		self['title'] = Label(_('Manual Installation'))
		self['key_red'] = Label(_('Cancel'))
		self['key_yellow'] = Label(_('Reload /tmp'))
		self['conn'].hide()
		self.isSettings = False
		self.container = eConsoleAppContainer()
		self.appClosed_conn = self.container.appClosed.connect(self.runFinished)
		self['actions'] = ActionMap(['WizardActions', 'ColorActions'], 
			{
				'ok': self.KeyOk,
				'yellow': self.readTmp,
				'red': self.cancel,
				'back': self.cancel
			})
		self.onLayoutFinish.append(self.readTmp)
		self.onShown.append(self.setWindowTitle)

	def setWindowTitle(self):
		self.setTitle(_('Manual Installation'))

	def readTmp(self):
		del self.list[:]
		tmp_list =[]
		pkgs = listdir('/tmp')
		count = 0
		for fil in pkgs:
			if fil.find('.deb') != -1 or fil.find('.tbz2') != -1 or fil.find('.zip') != -1 or fil.find('.rar') != -1:
				rename('/tmp/' + fil, '/tmp/' + fil.replace(' ', '_'))
				tmp_list.append([fil.replace(' ', '_')])
				count += 1
		if len(tmp_list) > 0:
			for fil in tmp_list:
				self.list.append(fil)
		else:
			self['conn'].show()
			self['conn'].setText(_('Copy a file .tbz2|.deb|.zip|.rar\nvia FTP in /tmp.'))
		self['list'].setList(self.list)

	def KeyOk(self):
		self.filename = ""
		if not self.container.running():
			if len(self.list) > 0:
				selection = self['list'].getCurrent()
				self.filename = selection[0]
				msg = _('Do you want install the addon:\n%s?') % self.filename
				box = self.session.openWithCallback(self.installAddons, MessageBox, msg, MessageBox.TYPE_YESNO)
				box.setTitle(_('Install Addon'))
			else:
				self.close()

	def installAddons(self, answer):
		if answer is True:
			self['conn'].show()
			self['conn'].setText(_('Installing: %s.\nPlease wait...') % self.filename)
			if self.filename.find('.deb') != -1:
				print 'dpkg -i /tmp/%s' % self.filename
				self.container.execute('dpkg -i /tmp/' + self.filename)
			elif self.filename.find('.tbz2') != -1:
				self.container.execute('tar -jxvf /tmp/' + self.filename + ' -C /')
			elif self.filename.find('.zip') != -1:
				if self.CheckIfSettings('zip') == 'settings':
					msg = _('Settings file detected: do you want to clean old settings?')
					box = self.session.openWithCallback(self.ManualZipSettingsInstall, MessageBox, msg, MessageBox.TYPE_YESNO)
					box.setTitle(_('Manual settings install'))
				else:
					self.session.openWithCallback(self.DirectoryBrowserClosed, ManualSelection)
			elif self.filename.find('.rar') != -1:
				if self.CheckIfSettings('rar') == 'settings':
					msg = _('Settings file detected: do you want to clean old settings?')
					box = self.session.openWithCallback(self.ManualRarSettingsInstall, MessageBox, msg, MessageBox.TYPE_YESNO)
					box.setTitle(_('Manual settings install'))
				else:
					self.session.openWithCallback(self.DirectoryBrowserClosed, ManualSelection)
			else:
				self['conn'].setText(_('File: %s\nis not a valid package!') % self.filename)

	def CheckIfSettings(self, compression):
		if compression == 'zip':
			print 'Check if it is zip settings'
			zipfiletype = popen('unzip -l /tmp/' + self.filename, 'r').readlines()
			for item in zipfiletype:
				if item.find('lamedb') != -1:
					self.isSettings = True
					return 'settings'

		elif compression == 'rar':
			print 'Check if it is rar settings'
			rarfiletype = popen('unrar l /tmp/' + self.filename, 'r').readlines()
			for item in rarfiletype:
				if item.find('lamedb') != -1:
					self.isSettings = True
					return 'settings'

		else:
			return 'Other'

	def DirectoryBrowserClosed(self, path):
		print 'PathBrowserClosed:' + str(path)
		if path != False:
			if self.filename.find('.zip') != -1:
				print 'unzip -o /tmp/' + self.filename + ' -d ' + str(path)
				self.container.execute('unzip -o /tmp/' + self.filename + ' -d ' + str(path))
			elif self.filename.find('.rar') != -1:
				self.container.execute('unrar e -o+ /tmp/' + self.filename + ' ' + str(path) + '/')

	def ManualZipSettingsInstall(self, answer):
		if answer:
			self.removeSetting()
		self['conn'].setText(_('Installing new settings...'))
		self.container.execute('unzip -o /tmp/' + self.filename + ' -d /etc/enigma2/')

	def ManualRarSettingsInstall(self, answer):
		if answer:
			self.removeSetting()
		self['conn'].setText(_('Installing new settings...'))
		self.container.execute('unrar e -o+ /tmp/' + self.filename + ' /etc/enigma2/')

	def runFinished(self, retval):
		print 'Fine self container execute Manual install'
		if self.isSettings:
			self.reloadSetting()
		else:
			plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
		system('rm -f /tmp/' + self.filename)
		self['conn'].setText(_('Addon: %s\ninstalled succesfully!') % self.filename)
		self.readTmp()
		if fileExists('/tmp/.restartE2'):
			system('rm -f /tmp/.restartE2')
			msg = 'Enigma2 will be now hard restarted to complete package installation.\nDo You want restart enigma2 now?'
			box = self.session.openWithCallback(self.restartEnigma2, MessageBox, msg, MessageBox.TYPE_YESNO)
			box.setTitle('Restart enigma')

	def cancel(self):
		if not self.container.running():
			del self.container
			self.close()
		else:
			self.container.kill()
			self['conn'].setText(_('Process Killed by user.\nAddon not installed correctly!'))

	def restartEnigma2(self, answer):
		if answer:
			self.session.open(TryQuitMainloop, 3)
	def reloadSetting(self):
		print 'Reload settings'
		self.eDVBDB = eDVBDB.getInstance()
		self.eDVBDB.reloadServicelist()
		self.eDVBDB.reloadBouquets()
	def removeSetting(self):
		print 'Remove settings'
		system('rm -f /etc/enigma2/*.radio')
		system('rm -f /etc/enigma2/*.tv')
		system('rm -f /etc/enigma2/lamedb')
		system('rm -f /etc/enigma2/blacklist')
		system('rm -f /etc/enigma2/whitelist')