from Screen import Screen
from Components.Button import Button
from Components.ActionMap import HelpableActionMap, ActionMap, NumberActionMap
from Components.MenuList import MenuList
from Components.MovieList import MovieList
from Components.DiskInfo import DiskInfo
from Components.Pixmap import Pixmap
from Components.Label import Label
from Components.PluginComponent import plugins
from Components.config import config, ConfigSubsection, ConfigText, ConfigInteger, ConfigLocations, ConfigSet, ConfigYesNo
from Components.Sources.ServiceEvent import ServiceEvent
from Components.UsageConfig import defaultMoviePath

from Plugins.Plugin import PluginDescriptor

from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.LocationBox import MovieLocationBox
from Screens.HelpMenu import HelpableScreen

from Tools.Directories import fileExists, resolveFilename, SCOPE_HDD
from Tools.BoundFunction import boundFunction

from enigma import eServiceReference, eServiceCenter, eTimer, eSize
from timer import TimerEntry

from os import path as os_path

# Dr.Best: folder in movielist
from enigma import eConsoleAppContainer

#Dr.Best: move Movie
from os import path as os_path
import merlin._merlin_filemover
from merlin.merlin_filemover import eFileMover
from Components.Merlin import MerlinImage
from merlin.emerlin import eMerlin

from Components.Renderer.VideoWidget import VideoWidget

config.movielist = ConfigSubsection()
config.movielist.moviesort = ConfigInteger(default=MovieList.SORT_RECORDED)
config.movielist.listtype = ConfigInteger(default=MovieList.LISTTYPE_ORIGINAL)
config.movielist.description = ConfigInteger(default=MovieList.HIDE_DESCRIPTION)
config.movielist.last_videodir = ConfigText(default=resolveFilename(SCOPE_HDD))
config.movielist.last_timer_videodir = ConfigText(default=resolveFilename(SCOPE_HDD))
config.movielist.videodirs = ConfigLocations(default=[resolveFilename(SCOPE_HDD)])
config.movielist.first_tags = ConfigText(default="")
config.movielist.second_tags = ConfigText(default="")
config.movielist.last_selected_tags = ConfigSet([], default=[])

def setPreferredTagEditor(te):
	global preferredTagEditor
	try:
		if preferredTagEditor == None:
			preferredTagEditor = te
			print "Preferred tag editor changed to ", preferredTagEditor
		else:
			print "Preferred tag editor already set to ", preferredTagEditor
			print "ignoring ", te
	except:
		preferredTagEditor = te
		print "Preferred tag editor set to ", preferredTagEditor

def getPreferredTagEditor():
	global preferredTagEditor
	return preferredTagEditor

setPreferredTagEditor(None)

class MovieContextMenu(Screen):

	def __init__(self, session, csel, service):
		Screen.__init__(self, session)
		self.csel = csel
		self.service = service

		self["actions"] = ActionMap(["OkCancelActions"],
			{
				"ok": self.okbuttonClick,
				"cancel": self.cancelClick
			})
			
		# Dr.Best selection mode
		if csel and csel["list"].getSelectionMode():
			if csel["list"].getSelectionMode() == 1: # Dr.Best delete mode
				menu = [(_("cancel delete mode..."), boundFunction(self.switchSelectionMode,0))]
			else: # Dr.Best moveTo mode
				menu = [(_("cancel move mode..."), boundFunction(self.switchSelectionMode,0))]
			if len(self.csel["list"].getSelectionList()) > 0:
				if csel["list"].getSelectionMode() == 1: # Dr.Best delete mode
					menu.append((_("delete all selected movies..."), self.deleteMovies))
				else: # Dr.Best moveTo mode
					menu.append((_("move all selected movies..."), self.moveToMovies))
			self["menu"] = MenuList(menu)
			return	

		menu = [(_("delete..."), self.delete)]
		# Dr.Best delete mode
		menu.append((_("activate delete mode..."), boundFunction(self.switchSelectionMode,1)))

		# Dr.Best: move Movie
		if not (self.service.flags & eServiceReference.mustDescent):
			menu.append((_("move..."), self.moveTo))

		# Dr.Best move mode
		menu.append((_("activate move mode..."), boundFunction(self.switchSelectionMode,2)))

		# Dr.Best set Movie Status
		menu.append((_("mark as seen..."), boundFunction(self.setMovieStatus, 1)))
		menu.append((_("mark as unseen..."), boundFunction(self.setMovieStatus, 0)))

		# Dr.Best: folder in movielist
		if not (self.service.flags & eServiceReference.mustDescent):
			menu.extend([(p.description, boundFunction(self.execPlugin, p)) for p in plugins.getPlugins(PluginDescriptor.WHERE_MOVIELIST)])
		elif (self.service.flags & eServiceReference.mustDescent):
			menu.extend([(p.description, boundFunction(self.execPlugin, p, "MOVIELISTFOLDER")) for p in plugins.getPlugins(PluginDescriptor.WHERE_MOVIELISTFOLDER)])			

		# Dr.Best: sort by date desc/asc
		if config.merlin2.use_custom_folder_moviesort.value:
			menu.append((_("alphabetic sort"), boundFunction(self.sortBy, MovieList.SORT_ALPHANUMERIC)))
			menu.append((_("sort by date desc"), boundFunction(self.sortBy, MovieList.SORT_DATE_DESC)))
			menu.append((_("sort by date asc"), boundFunction(self.sortBy, MovieList.SORT_DATE_ASC)))
		else:
			if config.movielist.moviesort.value == MovieList.SORT_ALPHANUMERIC:
				#menu.append((_("sort by date"), boundFunction(self.sortBy, MovieList.SORT_RECORDED)))
				menu.append((_("sort by date desc"), boundFunction(self.sortBy, MovieList.SORT_DATE_DESC)))
				menu.append((_("sort by date asc"), boundFunction(self.sortBy, MovieList.SORT_DATE_ASC)))
			else:
				menu.append((_("alphabetic sort"), boundFunction(self.sortBy, MovieList.SORT_ALPHANUMERIC)))
				if config.movielist.moviesort.value == MovieList.SORT_DATE_DESC:
					menu.append((_("sort by date asc"), boundFunction(self.sortBy, MovieList.SORT_DATE_ASC)))
				else:
					menu.append((_("sort by date desc"), boundFunction(self.sortBy, MovieList.SORT_DATE_DESC)))
		
		menu.extend((
			(_("list style default"), boundFunction(self.listType, MovieList.LISTTYPE_ORIGINAL)),
			(_("list style compact with description"), boundFunction(self.listType, MovieList.LISTTYPE_COMPACT_DESCRIPTION)),
			(_("list style compact"), boundFunction(self.listType, MovieList.LISTTYPE_COMPACT)),
			# Dr.Best: new listtype
			(_("list style Merlin2 single line"), boundFunction(self.listType, MovieList.LISTTYPE_MINIMAL_MERLIN)),
			(_("list style single line"), boundFunction(self.listType, MovieList.LISTTYPE_MINIMAL))
		))

		if config.movielist.description.value == MovieList.SHOW_DESCRIPTION:
			menu.append((_("hide extended description"), boundFunction(self.showDescription, MovieList.HIDE_DESCRIPTION)))
		else:
			menu.append((_("show extended description"), boundFunction(self.showDescription, MovieList.SHOW_DESCRIPTION)))

		# Dr.Best: video widget in movielist
		if self.csel.videoservice_widget_skin_supported:
			if config.merlin2.enable_video_widget.value:
				menu.append((_("hide video preview"), boundFunction(self.showVideoWidget, False)))
			else:
				menu.append((_("show video preview"), boundFunction(self.showVideoWidget, True)))

			# Dr.Best: disable ts in video widget in movielist
			if config.merlin2.disable_ts_in_video_widget.value:
				menu.append((_("enable TS files in video preview"), boundFunction(self.disableTSinVideoWidget, False)))
			else:
				menu.append((_("disable TS files in video preview"), boundFunction(self.disableTSinVideoWidget, True)))			

		# Dr.Best: folder in movielist
		if config.merlin2.showfoldersinmovielist.value:
			menu.append((_("hide folders in movielist"), boundFunction(self.showFolders, False)))
		else:
			menu.append((_("show folders in movielist"), boundFunction(self.showFolders, True)))

		# Dr.Best: color status in movielist
		if config.merlin2.showcolorstatusinmovielist.value:
			menu.append((_("hide movie color status in movielist"), boundFunction(self.showStatusColor, False)))
		else:
			menu.append((_("show movie color status in movielist"), boundFunction(self.showStatusColor, True)))

		
		#dre	
		if config.merlin2.showcoverinmovielist.value:
			menu.append((_("hide movie cover in movielist"), boundFunction(self.showMovieCover, False)))
		else:
			menu.append((_("show movie cover in movielist"), boundFunction(self.showMovieCover, True)))

			
		self["menu"] = MenuList(menu)
		
		self["menu"].onSelectionChanged.append(self.updateSummary)
		self.onShown.append(self.updateSummary)

	# Dr.Best selection mode
	def switchSelectionMode(self, status):
		self.csel.switchSelectionMode(status)
		self.close()

	# Dr.Best set Movie Status
	def setMovieStatus(self, status):
		self.csel.setMovieStatus(status)
		self.close()

	def okbuttonClick(self):
		self["menu"].getCurrent()[1]()

	def cancelClick(self):
		self.close(False)

	def sortBy(self, newType):
		config.movielist.moviesort.value = newType
		self.csel.setSortType(newType)
		self.csel.reloadList()
		self.close()

	def listType(self, newType):
		config.movielist.listtype.value = newType
		self.csel.setListType(newType)
		self.csel.list.redrawList()
		self.close()

	def showDescription(self, newType):
		config.movielist.description.value = newType
		self.csel.setDescriptionState(newType)
		self.csel.updateDescription()
		self.close()

	# Dr.Best: video widget in movielist
	def showVideoWidget(self,value):
		config.merlin2.enable_video_widget.value = value
		config.merlin2.enable_video_widget.save()
		if not value:
			self.csel["VideoService"].newService(eServiceReference())
		self.csel.reloadList()
		self.close()

	# Dr.Best: disable ts in video widget in movielist
	def disableTSinVideoWidget(self,value):
		config.merlin2.disable_ts_in_video_widget.value = value
		config.merlin2.disable_ts_in_video_widget.save()
		self.csel.reloadList()
		self.close()

	# Dr.Best: folder in movielist
	def showFolders(self,value):
		config.merlin2.showfoldersinmovielist.value = value
		config.merlin2.showfoldersinmovielist.save()
		self.csel.showFolders(value)
		self.csel.reloadList()
		self.close()

	# Dr.Best: color status in movielist
	def showStatusColor(self,value):
		config.merlin2.showcolorstatusinmovielist.value = value
		config.merlin2.showcolorstatusinmovielist.save()
		self.csel.showStatusColor(value)
		self.csel.reloadList()
		self.close()
	
	#dre
	def showMovieCover(self, value):
		config.merlin2.showcoverinmovielist.value = value
		config.merlin2.showcoverinmovielist.save()
		self.close()

	def execPlugin(self, plugin, type="MOVIELIST"):
		# Dr.Best: folder in movielist
		if not (self.service.flags & eServiceReference.mustDescent):
			plugin(session=self.session, service=self.service)
		elif (self.service.flags & eServiceReference.mustDescent) and type=="MOVIELISTFOLDER":
			plugin(session=self.session, service=self.service)

	def delete(self):
		serviceHandler = eServiceCenter.getInstance()
		info = serviceHandler.info(self.service)
		name = info and info.getName(self.service) or _("this recording")
		result = False
		# Dr.Best: folder in movielist
		if self.service.flags & eServiceReference.mustDescent:
			if self.service.getName() != "..":
				result = True
				name = self.service.getPath()
		else:
			# simulate first
			if not eMerlin.getInstance().deleteFromDisk(1,self.service):
				result = True
		if result == True:
			self.session.openWithCallback(self.deleteConfirmed, MessageBox, _("Do you really want to delete %s?") % (name))
		else:
			self.session.openWithCallback(self.close, MessageBox, _("You cannot delete this!"), MessageBox.TYPE_ERROR)

	def deleteConfirmed(self, confirmed):
		if not confirmed:
			return self.close()
		
		# Dr.Best: folder in movielist
		result = False
		if self.service.flags & eServiceReference.mustDescent:
			container = eConsoleAppContainer()
			container.execute("rm -rf '%s'" % self.service.getPath())
			result = True
		else:
			# really delete!
			if not eMerlin.getInstance().deleteFromDisk(0,self.service):
				result = True

		if result == False:
			self.session.openWithCallback(self.close, MessageBox, _("Delete failed!"), MessageBox.TYPE_ERROR)
		else:
			ref = self.session.nav.getCurrentlyPlayingServiceReference()
			if ref and (ref.getPath() == self.service.getPath()): # stop playing before deleting
				self.session.nav.stopService()
			self.stopRecording(self.service)
			self.csel["list"].removeService(self.service)
			self.csel["freeDiskSpace"].update()
			self.close()

	def stopRecording(self, service):
		from NavigationInstance import instance as navigationInstance
		servicepath = service.getPath()
		t = None
		if navigationInstance.getRecordings():
			for timer in navigationInstance.RecordTimer.timer_list:
				if timer.state == TimerEntry.StateRunning and timer.Filename and os_path.realpath(timer.Filename) == os_path.realpath(servicepath):
					t = timer
					break
		if not t:
			return
		elif t.repeated:  # do not delete repeated timer, just stop it for the current event
			t.enable()
			t.processRepeated(findRunningEvent = False)
			self.session.nav.RecordTimer.doActivate(t)
			self.session.nav.RecordTimer.timeChanged(t)
		else:
			self.session.nav.RecordTimer.removeEntry(t)

	# Dr.Best delete mode
	def deleteMovies(self):
		selectionList = self.csel["list"].getSelectionList()
		if len(selectionList):
			result = True
			for item in selectionList.items():
				ref = eServiceReference(item[0])
				if item[1]:
					# simulate first
					if eMerlin.getInstance().deleteFromDisk(1,ref):
						result = False
						break
			if result:
					self.session.openWithCallback(boundFunction(self.deleteMoviesConfirmed, selectionList), MessageBox, _("Do you really want to delete all selected movies?"))
			else:
				self.session.open(MessageBox, _("Something went wrong by trying to delete a physical file from the disc.\nOperation was cancelled, nothing was deleted!") , MessageBox.TYPE_ERROR) 
				self.switchSelectionMode(0)
		else:
			self.session.openWithCallback(boundFunction(self.switchSelectionMode, 0),MessageBox, _("Nothing selected to delete.\nDelete mode cancelled..."))
		
	# Dr.Best delete mode
	def deleteMoviesConfirmed(self, selectionList, confirmed):
		if not confirmed:
			self.close()
			return
		else:
			for item in selectionList.items():
				ref = eServiceReference(item[0])
				if item[1]:
					self.stopRecording(ref) # Dr.Best: check for current recording and stop it without questioning
					if self.session.nav.getCurrentlyPlayingServiceReference() is not None and self.session.nav.getCurrentlyPlayingServiceReference().getPath() == ref.getPath(): # Dr. Best --> stop playing before deleting
						self.session.nav.stopService()
					if not eMerlin.getInstance().deleteFromDisk(0,ref):
						self.csel["list"].removeService(ref)
		self.csel["freeDiskSpace"].update()
		self.switchSelectionMode(0)

	# Dr.Best: move Movie
	def moveTo(self):
		self.session.openWithCallback(
			self.moveToPathSelected,
			MovieLocationBox,
			_("Please select the movie path..."),
			config.movielist.last_videodir.value
		)

	# Dr.Best: move Movie
	def moveToPathSelected(self, res):
		if res is not None and res is not config.movielist.last_videodir.value:
			result = False
			if fileExists(res):
				serviceHandler = eServiceCenter.getInstance()
				info = serviceHandler.info(self.service)
				name = info and info.getName(self.service) or _("this recording")
				self.session.openWithCallback(boundFunction(self.moveToConfirmed,res), MessageBox, _("Do you really want to move %s\nfrom folder: %s\nto destination folder: %s ?") % (name, os_path.dirname(self.service.getPath()), res))
			else:
				self.session.open(
					MessageBox,
					_("Directory %s nonexistent.") % (res),
					type = MessageBox.TYPE_ERROR,
					timeout = 5
					)

	# Dr.Best: move Movie
	def moveToConfirmed(self, destination, confirmed):
		if not confirmed:
			return self.close()
		if self.session.nav.getCurrentlyPlayingServiceReference() is not None and self.session.nav.getCurrentlyPlayingServiceReference().getPath() == self.service.getPath(): # Dr. Best --> stop playing before moving
			self.session.nav.stopService()
		eFileMover.moveTo(self.service.getPath(), destination)	
		self.csel["list"].removeService(self.service)
		self.csel["freeDiskSpace"].update()
		self.close()

	# Dr.Best: move mode
	def moveToMovies(self):
		selectionList = self.csel["list"].getSelectionList()
		if len(selectionList):
			self.session.openWithCallback(self.moveToMoviesPathSelected, MovieLocationBox, _("Please select the movie path..."), config.movielist.last_videodir.value)
		else:
			self.session.openWithCallback(boundFunction(self.switchSelectionMode, 0),MessageBox, _("Nothing selected to move.\nMove mode cancelled..."))

	# Dr.Best: move mode
	def moveToMoviesPathSelected(self, res):
		if res is not None and res is not config.movielist.last_videodir.value:
			if fileExists(res):
				self.session.openWithCallback(boundFunction(self.moveToMoviesConfirmed,res), MessageBox, _("Do you really want to move all selected movies to destination folder: %s ?") % res)
			else:
				self.session.open(MessageBox, _("Directory %s nonexistent.") % (res), type = MessageBox.TYPE_ERROR, timeout = 5)

	# Dr.Best: move mode
	def moveToMoviesConfirmed(self, destination, confirmed):
		if not confirmed:
			self.close()
			return 
		selectionList = self.csel["list"].getSelectionList()
		for item in selectionList.items():
			ref = eServiceReference(item[0])
			if item[1]:
				if self.session.nav.getCurrentlyPlayingServiceReference() is not None and self.session.nav.getCurrentlyPlayingServiceReference().getPath() == ref.getPath(): # Dr. Best --> stop playing before moving
					self.session.nav.stopService()
				eFileMover.moveTo(ref.getPath(), destination)	
				self.csel["list"].removeService(ref)
		self.csel["freeDiskSpace"].update()
		self.switchSelectionMode(0)

	def createSummary(self):
		return MovieContextMenuSummary	

	def updateSummary(self):
		text = self["menu"].getCurrent()[0]
		self.summaries.setText(text)

class SelectionEventInfo:
	def __init__(self):
		self["Service"] = ServiceEvent()
		self["ServiceInfo"] = ServiceEvent()
		self.list.connectSelChanged(self.__selectionChanged)
		self.timer = eTimer()
		self.timer_conn = self.timer.timeout.connect(self.updateEventInfo)
		self.onShown.append(self.__selectionChanged)

	def __selectionChanged(self):
		if self.execing: # and config.movielist.description.value == MovieList.SHOW_DESCRIPTION:
			self.timer.start(100, True)

	def updateEventInfo(self):
		serviceref = self.getCurrent()
		self["ServiceInfo"].newService(serviceref)
		if config.movielist.description.value == MovieList.SHOW_DESCRIPTION:
			self["Service"].newService(serviceref)

class SelectionCoverInfo:
	def __init__(self):
		self["CoverService"] = ServiceEvent()
		self.list.connectSelChanged(self.__selectionChangedForCover)
		self.coverTimer = eTimer()
		self.coverTimer_conn = self.coverTimer.timeout.connect(self.updateCover)
		self.showCover = False
		self.onShown.append(self.__selectionChangedForCover)

	def __selectionChangedForCover(self):
		if self.execing and config.merlin2.showcoverinmovielist.value:
			self.showCover = True
			self.coverTimer.start(100, True)
		elif self.showCover and not config.merlin2.showcoverinmovielist.value:
			self.showCover = False
			self["CoverService"].newService(None)

	def updateCover(self):
		serviceref = self.getCurrent()
		self["CoverService"].newService(serviceref)

class SelectionVideoPreview:
	def __init__(self):
		self["VideoService"] = ServiceEvent()
		self.list.connectSelChanged(self.__selectionChangedForVideo)
		self.videoTimer = eTimer()
		self.videoTimer_conn = self.videoTimer.timeout.connect(self.updateVideo)
		self.onShown.append(self.__selectionChangedForVideo)

	def __selectionChangedForVideo(self):
		if self.execing and self.videoservice_widget_skin_supported and config.merlin2.enable_video_widget.value:
			self.videoTimer.start(500, True)

	def updateVideo(self):
		serviceref = self.getCurrent()
		if serviceref:
			self["VideoService"].newService(serviceref)

class MovieSelection(Screen, HelpableScreen, SelectionEventInfo, SelectionCoverInfo, SelectionVideoPreview):
	def __init__(self, session, selectedmovie = None):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)

		self.tags = [ ]
		if selectedmovie:
			self.selected_tags = config.movielist.last_selected_tags.value
		else:
			self.selected_tags = None
		self.selected_tags_ele = None

		self.movemode = False
		self.bouquet_mark_edit = False

		self.delayTimer = eTimer()
		self.delayTimer_conn = self.delayTimer.timeout.connect(self.updateHDDData)

		self["waitingtext"] = Label(_("Please wait... Loading list..."))

		# create optional description border and hide immediately
		self["DescriptionBorder"] = Pixmap()
		self["DescriptionBorder"].hide()

		if not fileExists(config.movielist.last_videodir.value):
			config.movielist.last_videodir.value = defaultMoviePath()
			config.movielist.last_videodir.save()
		self.current_ref = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + config.movielist.last_videodir.value)

		# Dr.Best: folder in movielist and color staus in movielist
		self["list"] = MovieList(None,
			config.movielist.listtype.value,
			config.movielist.moviesort.value,
			config.movielist.description.value,
			config.merlin2.showfoldersinmovielist.value,
			config.merlin2.showcolorstatusinmovielist.value)

		self.list = self["list"]
		self.selectedmovie = selectedmovie

		# Need list for init
		SelectionEventInfo.__init__(self)

		SelectionCoverInfo.__init__(self)
		SelectionVideoPreview.__init__(self)		
		
		self["key_red"] = Button(_("All"))
		self["key_green"] = Button("")
		self["key_yellow"] = Button("")
		self["key_blue"] = Button("")

		self["freeDiskSpace"] = self.diskinfo = DiskInfo(config.movielist.last_videodir.value, DiskInfo.FREE, update=False)

		if config.usage.setup_level.index >= 2: # expert+
			self["InfobarActions"] = HelpableActionMap(self, "InfobarActions", 
				{
					"showMovies": (self.doPathSelect, _("select the movie path")),
				})


		self["MovieSelectionActions"] = HelpableActionMap(self, "MovieSelectionActions",
			{
				"contextMenu": (self.doContext, _("menu")),
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["ColorActions"] = HelpableActionMap(self, "ColorActions",
			{
				"red": (self.showAll, _("show all")),
				"green": (self.showTagsFirst, _("show first selected tag")),
				"yellow": (self.showTagsSecond, _("show second selected tag")),
				"blue": (self.showTagsSelect, _("show tag menu")),
			})

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"cancel": (self.abort, _("exit movielist")),
				"ok": (self.movieSelected, _("select movie")),
			})

		# Dr.Best: folder in movielist
		self["actions2"] = NumberActionMap(["InputActions"],
		{
			"0": self.keyNumber_pressed,
		}, -1)
		
		
		# Dr.Best --> MovieFileList
		self["MovieFileListPlay"] = HelpableActionMap(self, "MediaPlayerActions",
			{
				"pause": (self.movieSelectedAll, _("play all files in directory")),
			})
		
		if config.merlin2.enable_picture_view_in_movielist.value:
			MerlinImage.imageExtensions(1)
			self.onClose.append(self.disableImageExtensions)

		self.videoservice_widget_skin_supported = False

		self.onShown.append(self.go)
		self.onLayoutFinish.append(self.saveListsize)
		self.inited = False

	def disableImageExtensions(self):
		MerlinImage.imageExtensions(0)

	# Dr.Best: folder in movielist
	def keyNumber_pressed(self, number):
		if config.merlin2.showfoldersinmovielist.value:
			if number == 0:
				self["list"].moveToIndex(0)
				current = self.getCurrent()
				if current is not None:
					if (current.flags & eServiceReference.mustDescent) and current.getName() == "..":
						self.gotFilename(current.getPath())			

	def updateDescription(self):
		if config.movielist.description.value == MovieList.SHOW_DESCRIPTION:
			self["DescriptionBorder"].show()
			self["list"].instance.resize(eSize(self.listWidth, self.listHeight-self["DescriptionBorder"].instance.size().height()))
		else:
			self["Service"].newService(None)
			self["DescriptionBorder"].hide()
			self["list"].instance.resize(eSize(self.listWidth, self.listHeight))

	def showEventInformation(self):
		from Screens.EventView import EventViewSimple
		from ServiceReference import ServiceReference
		evt = self["list"].getCurrentEvent()
		if evt:
			self.session.open(EventViewSimple, evt, ServiceReference(self.getCurrent()))

	def go(self):
		if not self.inited:
		# ouch. this should redraw our "Please wait..."-text.
		# this is of course not the right way to do this.
			for renderer in self.renderer:
				if isinstance(renderer, VideoWidget):
					self.videoservice_widget_skin_supported = True
					break
			self.delayTimer.start(300, 1)
			self.inited=True

	def saveListsize(self):
			listsize = self["list"].instance.size()
			self.listWidth = listsize.width()
			self.listHeight = listsize.height()
			self.updateDescription()

	def updateHDDData(self):
 		self.reloadList(self.selectedmovie)
		self["waitingtext"].visible = False

	def moveTo(self):
		self["list"].moveTo(self.selectedmovie)

	def getCurrent(self):
		return self["list"].getCurrent()


	# Dr.Best delete mode
	def switchSelectionMode(self, status):
		self["list"].switchSelectionMode(status)

	# Dr.Best set Movie Status
	def setMovieStatus(self, status):
		current = self.getCurrent()
		if current is not None:
			self["list"].setMovieStatus(current,status)

	def movieSelected(self):
		current = self.getCurrent()
		if current is not None:
			# Dr.Best: folder in movielist
			if current.flags & eServiceReference.mustDescent:
				self.gotFilename(current.getPath())
			else:
				# Dr.Best selection mode
				if self["list"].getSelectionMode():
					self["list"].setDeleteValue(current)
				else:
					self.saveconfig()
					self.close(current)
					
	# Dr.Best --> MovieFileList
	def movieSelectedAll(self):
		current = self.getCurrent()
		if current is not None and not (current.flags & eServiceReference.mustDescent) and not self["list"].getSelectionMode():
			  self.saveconfig()
			  self.close(current, True)
				
	def doContext(self):
		current = self.getCurrent()
		if current is not None:
			if config.merlin2.useMerlinContextMenu.value:
				from Screens.MovieSelectionMerlinContextMenu import MovieSelectionMerlinContextMenu #dre: MerlinContextMenu
				self.session.open(MovieSelectionMerlinContextMenu, self, current)
			else:
				self.session.open(MovieContextMenu, self, current)

	def abort(self):
		self.saveconfig()
		self.close(None)

	def saveconfig(self):
		config.movielist.last_selected_tags.value = self.selected_tags
		config.movielist.moviesort.save()
		config.movielist.listtype.save()
		config.movielist.description.save()

	def getTagDescription(self, tag):
		# TODO: access the tag database
		return tag

	def updateTags(self):
		# get a list of tags available in this list
		self.tags = list(self["list"].tags)

		if not self.tags:
			# by default, we do not display any filtering options
			self.tag_first = ""
			self.tag_second = ""
		else:
			tmp = config.movielist.first_tags.value
			if tmp in self.tags:
				self.tag_first = tmp
			else:
				self.tag_first = "<"+_("Tag 1")+">"
			tmp = config.movielist.second_tags.value
			if tmp in self.tags:
				self.tag_second = tmp
			else:
				self.tag_second = "<"+_("Tag 2")+">"
		self["key_green"].text = self.tag_first
		self["key_yellow"].text = self.tag_second
		
		# the rest is presented in a list, available on the
		# fourth ("blue") button
		if self.tags:
			self["key_blue"].text = _("Tags")+"..."
		else:
			self["key_blue"].text = ""

	def setListType(self, type):
		self["list"].setListType(type)

	def setDescriptionState(self, val):
		self["list"].setDescriptionState(val)

	def setSortType(self, type):
		self["list"].setSortType(type)

	# Dr.Best: folder in movielist
	def showFolders(self, val):
		self["list"].showFolders(val)

	# Dr.Best: color status in movielist
	def showStatusColor(self,value):
		self["list"].showStatusColor(value)

	def reloadList(self, sel = None, home = False):
		if not fileExists(config.movielist.last_videodir.value):
			path = defaultMoviePath()
			config.movielist.last_videodir.value = path
			config.movielist.last_videodir.save()
			self.current_ref = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + path)
			self["freeDiskSpace"].path = path
		if sel is None:
			sel = self.getCurrent()
		self["list"].reload(self.current_ref, self.selected_tags)
		title = _("Recorded files...")
		if config.usage.setup_level.index >= 2: # expert+
			title += "  " + config.movielist.last_videodir.value
		if self.selected_tags is not None:
			title += " - " + ','.join(self.selected_tags)
		self.setTitle(title)
 		if not (sel and self["list"].moveTo(sel)):
			if home:
				self["list"].moveToIndex(0)
		self.updateTags()
		self["freeDiskSpace"].update()

	def doPathSelect(self):
		self.session.openWithCallback(
			self.gotFilename,
			MovieLocationBox,
			_("Please select the movie path..."),
			config.movielist.last_videodir.value
		)

	def gotFilename(self, res):
		if res is not None and res is not config.movielist.last_videodir.value:
			if fileExists(res):
				# Dr.Best: folder in movielist			
				selection = None # get the current path when navigation to a higher folder by selecting  ".." , then select the folder-item in the new list
				current = self.getCurrent()
				if current is not None:
					if current.flags & eServiceReference.mustDescent:				
						if current.getName() == "..":
							selection = eServiceReference("2:47:1:0:0:0:0:0:0:0:" + self["list"].root.getPath())
							
				config.movielist.last_videodir.value = res
				config.movielist.last_videodir.save()
				self.current_ref = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + res)
				self["freeDiskSpace"].path = res
				self.reloadList(sel = selection, home = True) # Dr.Best: folder in movielist
			else:
				self.session.open(
					MessageBox,
					_("Directory %s nonexistent.") % (res),
					type = MessageBox.TYPE_ERROR,
					timeout = 5
					)

	def showAll(self):
		self.selected_tags_ele = None
		self.selected_tags = None
		self.reloadList(home = True)

	def showTagsN(self, tagele):
		if not self.tags:
			self.showTagWarning()
		elif not tagele or (self.selected_tags and tagele.value in self.selected_tags) or not tagele.value in self.tags:
			self.showTagsMenu(tagele)
		else:
			self.selected_tags_ele = tagele
			self.selected_tags = set([tagele.value])
			self.reloadList(home = True)

	def showTagsFirst(self):
		self.showTagsN(config.movielist.first_tags)

	def showTagsSecond(self):
		self.showTagsN(config.movielist.second_tags)

	def showTagsSelect(self):
		self.showTagsN(None)

	def tagChosen(self, tag):
		if tag is not None:
			self.selected_tags = set([tag[0]])
			if self.selected_tags_ele:
				self.selected_tags_ele.value = tag[0]
				self.selected_tags_ele.save()
			self.reloadList(home = True)

	def showTagsMenu(self, tagele):
		self.selected_tags_ele = tagele
		list = [(tag, self.getTagDescription(tag)) for tag in self.tags ]
		self.session.openWithCallback(self.tagChosen, ChoiceBox, title=_("Please select tag to filter..."), list = list)

	def showTagWarning(self):
		self.session.open(MessageBox, _("No tags are set on these movies."), MessageBox.TYPE_ERROR)

class MovieContextMenuSummary(Screen):
	skin = (
		"""
		<screen name="MovieContextMenuSummary" position="0,0" size="132,64" id="1">
			<widget name="entry" position="5,5" size="122,54" halign="center" valign="center" font="Regular;25" />
		</screen>""",
		"""
		<screen name="MovieContextMenuSummary" position="0,0" size="96,64" id="2">
			<widget name="entry" position="5,5" size="86,54" halign="center" valign="center" font="Regular;25" />
		</screen>""",	
		"""
		<screen name="MovieContextMenuSummary" position="0,0" size="400,240" id="3">
			<widget name="entry" position="5,5" size="390,230" halign="center" valign="center" font="Regular;40" />
		</screen>""",
		"""
		<screen name="MovieContextMenuSummary" position="0,0" size="240,80" id="100">
			<widget name="entry" position="5,5" size="230,70" halign="center" valign="center" font="Regular;30" />
		</screen>"""
		)
		
	def __init__(self, session, parent):
		Screen.__init__(self, session)
		self["entry"] = Label()
		
	def setText(self, text):
		self["entry"].setText(text)
