#
#  SpinnerSelection
#
#  Coded by Dr.Best (c) 2011
#  Support: www.dreamboxtools.de
#
#  This plugin is licensed under the Creative Commons 
#  Attribution-NonCommercial-ShareAlike 3.0 Unported 
#  License. To view a copy of this license, visit
#  http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative
#  Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
#
#  Alternatively, this plugin may be distributed and executed on hardware which
#  is licensed by Dream Multimedia GmbH.

#  This plugin is NOT free software. It is open source, you are allowed to
#  modify it (if you keep the license), but it may not be commercially 
#  distributed other than under the conditions noted above.
#


from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from enigma import eTimer, loadPNG, ePixmap, eEnv
from Components.config import config
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Components.Sources.StaticText import StaticText
from Components.Pixmap import Pixmap
from os import path as os_path
from Components.FileList import FileList

MAX_SPINNER = 64

class SpinnerSelection(Screen):

	skin = """
		<screen name="SpinnerSelection" position="center,center" size="560,450" title="Spinner Selection">
			<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" 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" 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" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget render="Label" source="key_blue" position="420,0" size="140,40" zPosition="5" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget name="filelist" position="10,50" zPosition="1" size="540,250" scrollbarMode="showOnDemand"/>
			<widget render="Label" source="preview" position="10,320" zPosition="1" size="200,23" font="Regular;22" transparent="1"/>
			<widget name="spinnerpreview" zPosition="1" position="10,350" size="200,90" alphatest="blend"/>
			<widget render="Label" source="current" position="460,320" zPosition="1" size="90,23" font="Regular;22" transparent="1"/>
			<widget name="currentspinner" zPosition="2" position="460,350" size="90,90" alphatest="blend"/>
		</screen>
		""" 

	def __init__(self, session):
		Screen.__init__(self, session)
		self["currentspinner"] = SpinnerPreview()
		self["spinnerpreview"] = SpinnerPreview()
		self["preview"] = StaticText(_("Preview"))
		self["current"] = StaticText(_("Current"))
		self["key_blue"] = StaticText(_("Default"))
		self["key_yellow"] = StaticText()
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("OK"))

		inhibitDirs = ["/bin", "/boot", "/dev", "/lib", "/proc", "/sbin", "/sys", "/usr", "/var", "/share"]
		inhibitMounts = []
		self["filelist"] = FileList("/media/usb/", showDirectories = True, showFiles = False, inhibitMounts = inhibitMounts, inhibitDirs = inhibitDirs)
		self["actions"] = ActionMap(["WizardActions", "DirectionActions", "ColorActions", "EPGSelectActions"],
		{
			"back": self.cancel,
			"left": self.left,
			"right": self.right,
			"up": self.up,
			"down": self.down,
			"ok": self.ok,
			"blue": self.default,
			"red": self.cancel,
			"green": self.save,

		}, -1)

		self.spinner = config.misc.customSpinnerPath.value
		self.onLayoutFinish.append(self.startRun)

	def startRun(self):
		if self.spinner != "":
			self["currentspinner"].loadSpinner(self.spinner)			
		else:
			self["currentspinner"].loadSpinner(eEnv.resolve('${datadir}/enigma2/skin_default/spinner/'))

	def cancel(self):
		self.close()

	def save(self):
		config.misc.customSpinnerPath.value = self.spinner
		config.misc.customSpinnerPath.save()
		restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart.\nDo you want to restart the GUI now?"), MessageBox.TYPE_YESNO)
		restartbox.setTitle(_("Restart GUI now?"))

	def default(self):
		self["spinnerpreview"].loadSpinner(eEnv.resolve('${datadir}/enigma2/skin_default/spinner/'))
		self.spinner = ""

	def up(self):
		self["filelist"].up()
		self.updateTarget()

	def down(self):
		self["filelist"].down()
		self.updateTarget()

	def left(self):
		self["filelist"].pageUp()
		self.updateTarget()

	def right(self):
		self["filelist"].pageDown()
		self.updateTarget()

	def ok(self):
		if self["filelist"].canDescent():
			self["filelist"].descent()
			self.updateTarget()

	def updateTarget(self):
		currFolder = self["filelist"].getSelection()[0]
		self.spinner = ""
		if currFolder is not None:
			self["spinnerpreview"].loadSpinner(currFolder)
			if self["spinnerpreview"].spinnerAvailable():
				self.spinner = currFolder
		else:
			self["spinnerpreview"].clear()


	def restartGUI(self, answer):
		if answer is True:
			self.session.open(TryQuitMainloop, 3)
		else:
			self.close()

				
class SpinnerPreview(Pixmap):
	def __init__(self):
		Pixmap.__init__(self)
		self.index = 0
		self.spinner = { }
		self.spinnerTimer = eTimer()
		self.spinnerTimer_Connection = self.spinnerTimer.timeout.connect(self.updateSpinner)

	def loadSpinner(self, path):
		self.clear()
		i = 0
		while True:
			i += 1
			spinner_file = "wait%d.png" % (i)
			filename = os_path.join(path, spinner_file)
			if os_path.exists(filename):
				self.spinner[str(i)] = loadPNG(filename)
			else:
				break
			if i > MAX_SPINNER or not self.spinner.get(str(i),None):
				break
		if len(self.spinner):
			self.updateSpinner()
			self.show()

	def spinnerAvailable(self):
		return len(self.spinner)

	def onShow(self):
		Pixmap.onShow(self)

	def clear(self):
		self.spinnerTimer.stop()
		self.spinner = { }
		self.index = 0
		self.hide()

	def updateSpinner(self):
		self.spinnerTimer.stop()
		self.index += 1
		if self.index > len(self.spinner):
			self.index = 1
		spinner_pic = self.spinner.get(str(self.index),None)
		if spinner_pic:
			self.instance.setPixmap(spinner_pic.__deref__())
		self.spinnerTimer.start(100)
