from __future__ import print_function
from Tools.Profile import profile

# workaround for required config entry dependencies.
from Screens.MovieSelection import MovieSelection

from Screen import Screen

profile("LOAD:enigma")
from enigma import iPlayableService

profile("LOAD:InfoBarGenerics")
from Screens.InfoBarGenerics import InfoBarShowHide, \
	InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarRdsDecoder, \
	InfoBarEPG, InfoBarSeek, InfoBarInstantRecord, \
	InfoBarAudioSelection, InfoBarAdditionalInfo, InfoBarDish, InfoBarUnhandledKey, \
	InfoBarSubserviceSelection, InfoBarShowMovies, InfoBarTimeshift,  \
	InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleEventView, \
	InfoBarSummarySupport, InfoBarMoviePlayerSummarySupport, InfoBarTimeshiftState, InfoBarTeletextPlugin, InfobarHbbtvPlugin, InfoBarExtensions, InfoBarNotifications, \
	InfoBarSubtitleSupport, InfoBarPiP, InfoBarPlugins, InfoBarServiceErrorPopupSupport, InfoBarJobman, InfoBarAutoSleepTimer, InfoBarGstreamerErrorPopupSupport

from Screens.InfoBarPrivate import InfoBarPrivateExtensions
profile("LOAD:InitBar_Components")
from Components.ActionMap import HelpableActionMap
from Components.config import config, ConfigBoolean
from Components.ServiceEventTracker import ServiceEventTracker, InfoBarBase
from Components.PluginComponent import plugins
from Plugins.Plugin import PluginDescriptor

profile("LOAD:HelpableScreen")
from Screens.HelpMenu import HelpableScreen

config.misc.initialharddisknotification = ConfigBoolean(True)
config.misc.missingdefaultstoragenotification = ConfigBoolean(False)

from Tools import Notifications
Notifications.notificationQueue.registerDomain("InfoBar", _("InfoBar"), Notifications.ICON_DEFAULT)

# Dr. Best Infobar position
from enigma import ePoint

#Dr. Best Select last played movie 
from enigma import eServiceReference

from struct import calcsize as struct_calcsize, unpack as struct_unpack, pack as struct_pack
from os import path as os_path, listdir as os_listdir

from enigma import eConsoleAppContainer

from Components.MovieList import MEDIACACHELIST
import NavigationInstance # Dr.Best stop potential currently recording before deleting a recording
from timer import TimerEntry # Dr.Best stop potential currently recording before deleting a recording

from enigma import eServiceCenter, iServiceInformation # Dr.Best --> MovieFileList
from Components.Merlin import MerlinImage, natural_keys
from merlin.emerlin import eMerlin
from Screens.MerlinPictureViewerScreen import MerlinPictureViewerScreen


try:
	from Plugins.Extensions.MerlinMusicPlayer2.plugin import isValidAudio, MerlinMusicPlayer2ScreenInfobar, Item
	use_mmp2 = True
except: use_mmp2 = False


class InfoBar(InfoBarBase, InfoBarShowHide,
	InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarEPG, InfoBarRdsDecoder,
	InfoBarInstantRecord, InfoBarAudioSelection,
	HelpableScreen, InfoBarAdditionalInfo, InfoBarDish, InfoBarUnhandledKey,
	InfoBarSubserviceSelection, InfoBarTimeshift, InfoBarSeek,
	InfoBarSummarySupport, InfoBarTimeshiftState, InfoBarTeletextPlugin, InfobarHbbtvPlugin, InfoBarExtensions, InfoBarNotifications,
	InfoBarPiP, InfoBarPlugins, InfoBarSubtitleSupport, InfoBarServiceErrorPopupSupport, InfoBarJobman, InfoBarAutoSleepTimer,
	InfoBarPrivateExtensions, InfoBarGstreamerErrorPopupSupport,
	Screen):

	ALLOW_SUSPEND = Screen.SUSPEND_STOPS
	instance = None

	def __init__(self, session):
		Screen.__init__(self, session)
		self["actions"] = HelpableActionMap(self, "InfobarActions",
			{
				"showMovies": (self.showMovies, _("Play recorded movies...")),
				"showRadio": (self.showRadio, _("Show the radio player...")),
				"showTv": (self.showTv, _("Show the tv player...")),
			}, prio=2)

		self.allowPiP = True

		for x in HelpableScreen, \
				InfoBarBase, InfoBarShowHide, \
				InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarEPG, InfoBarRdsDecoder, \
				InfoBarInstantRecord, InfoBarAudioSelection, InfoBarUnhandledKey, \
				InfoBarAdditionalInfo, InfoBarDish, InfoBarSubserviceSelection, \
				InfoBarTimeshift, InfoBarSeek, InfoBarSummarySupport, InfoBarTimeshiftState, \
				InfoBarTeletextPlugin, InfobarHbbtvPlugin, InfoBarExtensions, InfoBarNotifications, InfoBarPiP, InfoBarSubtitleSupport, InfoBarJobman, \
				InfoBarPlugins, InfoBarServiceErrorPopupSupport, InfoBarAutoSleepTimer, InfoBarPrivateExtensions, InfoBarGstreamerErrorPopupSupport:
			x.__init__(self)

		self.helpList.append((self["actions"], "InfobarActions", [("showMovies", _("view recordings..."))]))
		self.helpList.append((self["actions"], "InfobarActions", [("showRadio", _("hear radio..."))]))

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedEventInfo: self.__eventInfoChanged
			})

		self.current_begin_time=0
		assert InfoBar.instance is None, "class InfoBar is a singleton class and just one instance of this class is allowed!"
		InfoBar.instance = self
		for fnc in plugins.getPlugins(PluginDescriptor.WHERE_INFOBAR):
			fnc(session)

		self.showHarddiskPopup()

		self.onClose.append(self.__onClose)

		# Dr. Best Infobar position
		self.firstime = True # that is not nice :-(
		self.onExecBegin.append(self.__onExecBegin)

	def showHarddiskPopup(self, dev = None, media_state = None):
		from Components.Harddisk import harddiskmanager
		if not self.HDDDetectedCB in harddiskmanager.delayed_device_Notifier:
			harddiskmanager.delayed_device_Notifier.append(self.HDDDetectedCB)
		if config.misc.initialharddisknotification.value:
			from Screens.MessageBox import MessageBox
			if harddiskmanager.HDDCount() and not harddiskmanager.HDDEnabledCount():
				Notifications.AddNotificationWithCallback(self.HDDDetectedAnswer, MessageBox, _("Unconfigured storage devices found!")  + "\n" \
					+ _("Please make sure to set up your storage devices with the storage management in menu -> setup -> system -> storage devices.") + "\n\n" \
					+ _("Set up your storage device now?"), type = MessageBox.TYPE_YESNO, timeout = 15, default = False, domain = "InfoBar")
				config.misc.initialharddisknotification.value = False
				config.misc.initialharddisknotification.save()
		elif config.misc.missingdefaultstoragenotification.value and not config.misc.initialharddisknotification.value:
			from Screens.ChoiceBox import ChoiceBox
			from Components.UsageConfig import defaultStorageDevice
			choices = [
				(_("OK, do nothing"), "ok"),
				(_("OK, and don't ask again"), "ok_always")
			]
			if harddiskmanager.HDDCount():
				choices.append((_("OK, and set up a new default storage device"), "ok_setup"))
			titletxt = _("Default storage device is not available!") + "\n"
			if dev is None and defaultStorageDevice() != "<undefined>" and harddiskmanager.isDefaultStorageDeviceActivebyUUID(defaultStorageDevice()) is False:
				Notifications.AddNotificationWithCallback(self.missingDefaultHDDAnswer, ChoiceBox, title = titletxt \
					+ _("Please verify if your default storage device is attached or set up your default storage device in menu -> setup -> system -> storage devices.") + "\n", list = choices, domain = "InfoBar")
			elif dev is not None and defaultStorageDevice() != "<undefined>" and harddiskmanager.isDefaultStorageDeviceActivebyUUID(defaultStorageDevice()) is False:
				part = harddiskmanager.getPartitionbyDevice(dev)
				if part is not None and part.uuid is not None and media_state is not None and media_state == "remove_default":
					titletxt = _("Default storage device was removed!") + "\n"
					Notifications.AddNotificationWithCallback(self.missingDefaultHDDAnswer, ChoiceBox, title = titletxt \
						+ _("Please verify if your default storage device is attached or set up your default storage device in menu -> setup -> system -> storage devices.") + "\n", list = choices, domain = "InfoBar")

	def missingDefaultHDDAnswer(self, answer):
		answer = answer and answer[1]
		if answer is not None:
			if answer == "ok_always":
				print(answer)
				config.misc.missingdefaultstoragenotification.value = False
				config.misc.missingdefaultstoragenotification.save()
			elif answer == "ok_setup":
				print(answer)
				from Screens.HarddiskSetup import HarddiskDriveSelection
				self.session.open(HarddiskDriveSelection)

	def HDDDetectedAnswer(self, answer):
		if answer is not None:
			if answer:
				from Screens.HarddiskSetup import HarddiskDriveSelection
				self.session.open(HarddiskDriveSelection)

	def HDDDetectedCB(self, dev, media_state):
		if InfoBar.instance:
			if InfoBar.instance.execing:
				self.showHarddiskPopup(dev, media_state)
			else:
				print("HDDDetectedCB: main infobar is not execing... so we ignore hotplug event!")
		else:
				print("HDDDetectedCB: hotplug event.. but no infobar")

	# Dr. Best Infobar position
	def __onExecBegin(self):
		if self.firstime:
			orgpos = self.instance.position()	
			self.instance.move(ePoint(orgpos.x() + config.merlin2.infobar_position_offset_x.value, orgpos.y() + config.merlin2.infobar_position_offset_y.value))
			self.firstime = False

	def __onClose(self):
		InfoBar.instance = None

	def __eventInfoChanged(self):
		if self.execing:
			service = self.session.nav.getCurrentService()
			old_begin_time = self.current_begin_time
			info = service and service.info()
			ptr = info and info.getEvent(0)
			self.current_begin_time = ptr and ptr.getBeginTime() or 0
			if config.usage.show_infobar_on_event_change.value:
				if old_begin_time and old_begin_time != self.current_begin_time:
					self.doShow()

	def serviceStarted(self):  #override from InfoBarShowHide
		new = self.servicelist.newServicePlayed()
		if self.execing:
			InfoBarShowHide.serviceStarted(self)
			self.current_begin_time=0
		elif not self.__checkServiceStarted in self.onShown and new:
			self.onShown.append(self.__checkServiceStarted)

	def __checkServiceStarted(self):
		self.serviceStarted()
		self.onShown.remove(self.__checkServiceStarted)

	def showTv(self):
		self.showTvChannelList(True)

	def showRadio(self):
		if config.usage.e1like_radio_mode.value:
			self.showRadioChannelList(True)
		else:
			self.rds_display.hide() # in InfoBarRdsDecoder
			from Screens.MerlinChannelSelectionRadio import MerlinChannelSelectionRadio
			self.session.openWithCallback(self.ChannelSelectionRadioClosed, MerlinChannelSelectionRadio, self)

	def ChannelSelectionRadioClosed(self, *arg):
		self.rds_display.show()  # in InfoBarRdsDecoder

	def showMovies(self):
		#Dr. Best Select last played movie 
		if config.merlin2.movieplayer_select_last_seen_movie.value and config.merlin2.movieplayer_last_service.value != "":
			ref = eServiceReference(config.merlin2.movieplayer_last_service.value)
		else:
			ref = None
		self.session.openWithCallback(self.movieSelected, MovieSelection, ref)

	def showMoviesFromPictureViewer(self, filename):
		ref = eServiceReference(4097, 0, filename)
		self.session.openWithCallback(self.movieSelected, MovieSelection, ref)
		

	def movieSelected(self, service, *args, **kwargs):
		if service is not None:
			if use_mmp2 and isValidAudio(service.getPath()):
				slist = []
				foundIndex = 0
				index = 0
				files = os_listdir(os_path.dirname(service.getPath()))
				files.sort()
				for name in files:
					testname = os_path.join(os_path.dirname(service.getPath()), name)
					if isValidAudio(name):
						slist.append((Item(text = name, filename = testname),))
						if service.getPath().lower() == testname.lower():
							foundIndex = index
						index += 1
				config.merlin2.movieplayer_last_service.value = service.toString() 
				config.merlin2.movieplayer_last_service.save()
				self.session.openWithCallback(self.showMovies, MerlinMusicPlayer2ScreenInfobar, slist, foundIndex, False, self.session.nav.getCurrentlyPlayingServiceReference(), self.servicelist)
			elif config.merlin2.enable_picture_view_in_movielist.value and MerlinPictureViewerScreen.isValidPicture(service.getPath()):
				slist = []
				foundIndex = 0
				index = 0
				files = os_listdir(os_path.dirname(service.getPath()))
				files.sort(key=natural_keys)
				for name in files:
					if MerlinPictureViewerScreen.isValidPicture(name):
						testname = os_path.join(os_path.dirname(service.getPath()), name)
						slist.append(testname)
						if service.getPath().lower() == testname.lower():
							foundIndex = index
						index += 1
				if slist:
					self.session.openWithCallback(self.showMoviesFromPictureViewer, MerlinPictureViewerScreen, slist, foundIndex)
			else:
				# Dr.Best --> MovieFileList
				if args and args[0] == True:
				      list = self.getFileList(service)
				else:
				      list = []
				self.session.open(MoviePlayer, service, list)
	
# Dr.Best --> MovieFileList begin
	def getFileList(self, service):
		from Components.MovieList import MovieList
		serviceHandler = eServiceCenter.getInstance()
		root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + os_path.dirname(service.getPath())+"/")
		list = serviceHandler.list(root)
		files = [ ]
		while 1:
			serviceref = list.getNext()
			if not serviceref.valid():
				break
			if serviceref.flags & eServiceReference.mustDescent:
				continue
			info = serviceHandler.info(serviceref)
			if info is None:
				continue
			begin = info.getInfo(serviceref, iServiceInformation.sTimeCreate)
			files.append((serviceref,begin))
		if config.movielist.moviesort.value == MovieList.SORT_ALPHANUMERIC:
			files.sort(key=self.buildAlphaNumericSortKey)
		else:
			if config.movielist.moviesort.value ==  MovieList.SORT_DATE_ASC:
				files.sort(self.sortbyDateAsc)
			else:
				files.sort(self.sortbyDateDesc)
		list = []
		allowappend = False				    
		for file in files:
			if service.toString() == file[0].toString():
				allowappend = True
			elif allowappend:
				list.append(file[0])
		return list
				    
	def sortbyDateAsc(self, a, b):
		return cmp(a[1],b[1])

	def sortbyDateDesc(self, a, b):
		return cmp(b[1],a[1])

	def buildAlphaNumericSortKey(self, x):
		ref = x[0]
		serviceHandler = eServiceCenter.getInstance()
		info = serviceHandler.info(ref)
		name = info and info.getName(ref)
		return (name and name.lower() or "", -x[1])
# Dr.Best --> MovieFileList end

class MoviePlayer(InfoBarBase, InfoBarShowHide, \
		InfoBarMenu, \
		InfoBarSeek, InfoBarShowMovies, InfoBarAudioSelection, HelpableScreen,
		InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleEventView,
		InfoBarMoviePlayerSummarySupport, InfoBarSubtitleSupport, Screen, InfoBarTeletextPlugin,
		InfoBarServiceErrorPopupSupport, InfoBarExtensions, InfoBarNotifications, InfoBarPlugins, InfoBarPiP, InfoBarGstreamerErrorPopupSupport):

	ENABLE_RESUME_SUPPORT = True
	ALLOW_SUSPEND = Screen.SUSPEND_STOPS

	_answerQuit = "quit"
	_answerList = "movielist"
	_answerDeleteReturn = "deleteReturn"
	_answerDeleteQuit = "deleteQuit"
	_answerRestart = "restart"
	_answerContinue = "continue"
	_answerDeleteConfirmed = "deleteConfirmed"

	def __init__(self, session, service, filelist = []):
		Screen.__init__(self, session)
		self.filelist = filelist # Dr.Best --> MovieFileList
		self["actions"] = HelpableActionMap(self, "MoviePlayerActions",
			{
				"leavePlayer": (self.leavePlayer, _("leave movie player..."))
			})

		self.allowPiP = False

		for x in HelpableScreen, InfoBarShowHide, InfoBarMenu, \
				InfoBarBase, InfoBarSeek, InfoBarShowMovies, \
				InfoBarAudioSelection, InfoBarSimpleEventView, \
				InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, \
				InfoBarMoviePlayerSummarySupport, InfoBarSubtitleSupport, \
				InfoBarTeletextPlugin, InfoBarServiceErrorPopupSupport, InfoBarExtensions, InfoBarNotifications, \
				InfoBarPiP, InfoBarPlugins, InfoBarGstreamerErrorPopupSupport:
			x.__init__(self)

		self.is_closing = False
		self.returning = False
		self.onClose.append(self.onCloseRemoveNotifier)
		self._serviceName = _("this recording")
		self.movieSelected(service)

		# Dr. Best Infobar position
		self.firstime = True # that is not nice :-(
		self.onExecBegin.append(self.__onExecBegin)

		if config.merlin2.movieplayer_close_on_standby.value:
			config.misc.standbyCounter.addNotifier(self.standbyCounterChanged, initial_call = False)		
			
	def standbyCounterChanged(self, configElement):
		from Screens.Standby import inStandby
		if inStandby.prev_running_service:
			config.merlin2.movieplayer_last_service.value = inStandby.prev_running_service.toString() 
		else:
			config.merlin2.movieplayer_last_service.value = ""
		config.merlin2.movieplayer_last_service.save()
		inStandby.prev_running_service = self.lastservice
		inStandby.onClose.append(self.leaveStandby)

	def leaveStandby(self):
		self.close()

	# Dr. Best Infobar position
	def __onExecBegin(self):
		if self.firstime:
			orgpos = self.instance.position()	
			self.instance.move(ePoint(orgpos.x() + config.merlin2.movieplayer_infobar_position_offset_x.value, orgpos.y() + config.merlin2.movieplayer_infobar_position_offset_y.value))
			self.firstime = False

	def onCloseRemoveNotifier(self):
		if config.merlin2.movieplayer_close_on_standby.value and self.standbyCounterChanged in config.misc.standbyCounter.getNotifiers():
			config.misc.standbyCounter.removeNotifier(self.standbyCounterChanged)			

	def handleLeave(self, how):
		self.is_closing = True
		if how == "ask":
			if config.usage.setup_level.index < 1: # beginner
				lst = (
					(_("Quit"), self._answerQuit),
					(_("None"), self._answerContinue)
				)
			elif config.usage.setup_level.index < 2: # intermediate
				lst = (
					(_("Quit"), self._answerQuit),
					(_("Return to movie list"), self._answerList),
					(_("None"), self._answerContinue)
				)
			else: # expert
				lst = (
					(_("Quit"), self._answerQuit),
					(_("Return to movie list"), self._answerList),
					(_("Delete and return to movie list"), self._answerDeleteReturn),
					(_("Delete and quit "), self._answerDeleteQuit),
					(_("Restart from the beginning"), self._answerRestart),
					(_("None"),self._answerContinue),
				)

			from Screens.ChoiceBox import ChoiceBox
			self.session.openWithCallback(self.leavePlayerConfirmed, ChoiceBox, title=_("Action") , list = lst, windowTitle=self._serviceName)
		else:
			self.leavePlayerConfirmed([True, how])

	def leavePlayer(self):
		self.handleLeave(config.usage.on_movie_stop.value)

	def deleteConfirmed(self, answer):
		if answer:
			self.leavePlayerConfirmed((True, self._answerDeleteConfirmed))

	def leavePlayerConfirmed(self, answer):
		answer = answer and answer[1]
		#Dr. Best Select last played movie
		if self.session.nav.getCurrentlyPlayingServiceReference():
			config.merlin2.movieplayer_last_service.value = self.session.nav.getCurrentlyPlayingServiceReference().toString() 
		else:
			config.merlin2.movieplayer_last_service.value = ""

		if answer in (self._answerDeleteReturn, self._answerDeleteQuit, self._answerDeleteConfirmed):
			ref = self.session.nav.getCurrentlyPlayingServiceReference()
			name = self._serviceName

			if answer in (self._answerDeleteReturn, self._answerDeleteQuit):
				from Screens.MessageBox import MessageBox
				self.returning = answer == self._answerDeleteReturn
				self.session.openWithCallback(self.deleteConfirmed, MessageBox, _("Do you really want to delete %s?") % name)
				return

			elif answer == self._answerDeleteConfirmed:
				if eMerlin.getInstance().deleteFromDisk(0,ref):
					from Screens.MessageBox import MessageBox
					self.session.openWithCallback(self.close, MessageBox, _("You cannot delete this!"), MessageBox.TYPE_ERROR)
					return
				else:
					self.stopRecording(ref) # Dr.Best: check for current recording and stop it without questioning
					#Dr. Best Select last played movie 
					config.merlin2.movieplayer_last_service.value = ""

		#Dr. Best Select last played movie 
		config.merlin2.movieplayer_last_service.save()

		self.updateMovieData()	
					
		if self.returning and answer == self._answerDeleteConfirmed:
			answer = self._answerList
		if answer in (self._answerQuit, self._answerDeleteConfirmed):
			self.close()
		elif answer == self._answerList:
			ref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.returning = True
			self.session.openWithCallback(self.movieSelected, MovieSelection, ref)
			self.session.nav.stopService()
		elif answer == self._answerRestart:
			self.doSeek(0)
			self.setSeekState(self.SEEK_STATE_PLAY)

	def doEofInternal(self, playing):
		self.updateMovieData()
		if not self.execing:
			return
		if not playing :
			return
		if not hasattr(self,'filelist'):
			self.filelist = []
		if len(self.filelist) == 0:
			self.handleLeave(config.usage.on_movie_eof.value)
		else:
			service = self.filelist.pop(0)
			self.is_closing = False
			self.returning = False
			self.session.nav.playService(service)
			svc = self.session.nav.getCurrentService()
			info = svc and svc.info()
			self._serviceName = info and info.getName() or _("this recording")

	def showMovies(self):
		self.updateMovieData()
		ref = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.openWithCallback(self.movieSelected, MovieSelection, ref)

	def showMoviesAfterMMP2(self):
		self.session.openWithCallback(self.movieSelected, MovieSelection, eServiceReference(config.merlin2.movieplayer_last_service.value))

	def showMoviesFromPictureViewer(self, filename):
		ref = eServiceReference(4097, 0, filename)
		self.session.openWithCallback(self.movieSelected, MovieSelection, ref)
		

	def movieSelected(self, service, *args, **kwargs):
		self.updateMovieData()
		if service is not None:
			self.is_closing = False
			if use_mmp2 and isValidAudio(service.getPath()):
				slist = []
				foundIndex = 0
				index = 0
				files = os_listdir(os_path.dirname(service.getPath()))
				files.sort()
				for name in files:
					testname = os_path.join(os_path.dirname(service.getPath()), name)
					if isValidAudio(name):
						slist.append((Item(text = name, filename = testname),))
						if service.getPath().lower() == testname.lower():
							foundIndex = index
						index += 1
				self.session.nav.stopService()
				self.returning = True
				config.merlin2.movieplayer_last_service.value = service.toString() 
				config.merlin2.movieplayer_last_service.save()
				self.session.openWithCallback(self.showMoviesAfterMMP2, MerlinMusicPlayer2ScreenInfobar, slist, foundIndex, False, self.lastservice, InfoBar.instance.servicelist)
			elif config.merlin2.enable_picture_view_in_movielist.value and MerlinPictureViewerScreen.isValidPicture(service.getPath()):
				slist = []
				foundIndex = 0
				index = 0
				files = os_listdir(os_path.dirname(service.getPath()))
				files.sort(key=natural_keys)
				for name in files:
					if MerlinPictureViewerScreen.isValidPicture(name):
						testname = os_path.join(os_path.dirname(service.getPath()), name)
						slist.append(testname)
						if service.getPath().lower() == testname.lower():
							foundIndex = index
						index += 1
				if slist:
					self.session.openWithCallback(self.showMoviesFromPictureViewer, MerlinPictureViewerScreen, slist, foundIndex)
			else:
				if args and args[0] == True:
					self.filelist = InfoBar.instance.getFileList(service)
				else:
					self.filelist = []
				self.returning = False			
				self.session.nav.playService(service)
				svc = self.session.nav.getCurrentService()
				info = svc and svc.info()
				self._serviceName = info and info.getName() or _("this recording")
		elif self.returning:
			self.close()

	def updateMovieData(self):
		ref = self.session.nav.getCurrentlyPlayingServiceReference()
		if ref is not None and ref.type != 1: 
			extension = ref.getPath().split('.')[-1].lower()
			if extension in MerlinImage.getExtensions():
				seek = self.getSeek()
				if seek:
					pos = seek.getPlayPosition()
					length = seek.getLength()
					cutList = []
					cuts_format = ">QI" # big endian, unsigned long long, unsigned int
					cuts_format_size = struct_calcsize(cuts_format)
					packed_data = struct_pack(cuts_format,long(length[1]),1)
					cutList.append(packed_data)
					packed_data = struct_pack(cuts_format,long(pos[1]),3)
					cutList.append(packed_data)
					try:
						filename = os_path.realpath(ref.getPath())
						f = open("%s.cuts" % (filename), 'wb')
						f.write(''.join(cutList))
						f.close()
					except: pass
		if config.merlin2.use_mediacache.value:
			try:
				del MEDIACACHELIST[ref.toString()]
			except: pass

	# Dr.Best: check for current recording and stop it without questioning
	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)

