# -*- coding: utf-8 -*-
from gLocale import _
from GeminiDef import *
from plugin import libgeminimain, cgevent, quickSelectGlobal, PlayerNotifier
from FileBrowser import gBrowser 
from gTools import pathExists

from enigma import eServiceReference, eServiceCenter, iPlayableService, iServiceInformation
from Screens.InfoBar import MoviePlayer
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Components.ActionMap import ActionMap
from Components.ServiceEventTracker import ServiceEventTracker
from Components.Label import Label
from Components.config import config

from os import path as os_path

class StreamPlayer(MoviePlayer):
	def __init__(self, session, streamurl, streamname="", buffersize=None):
		MoviePlayer.__init__(self, session, self.__getService(streamurl))
		self.skinName = "StreamPlayer"

		self["actions"] = ActionMap(["gActions", "QuickButtonActions"],
		{
			"exit": self.KeyExit,
			"stop": self.KeyStop
		},-1)
		
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap={
			iPlayableService.evUpdatedEventInfo: self.__evUpdatedStreamInfo,
			})
		
		self["Streamname"] = Label(streamname)
		
		self.__exitmodus = cgevent.getConfig("Dmanager_movie_exit",1)
		self.__ChoiceBoxExe = None
		
		self.__downloadpath="/media/hdd/"
		if pathExists(config.usage.default_path.value):
			self.__downloadpath=config.usage.default_path.value
		self.onPlayStateChanged.append(self.__StateChanged)
		self.onClose.append(self.__onClose)
		
		if buffersize:
			self.SetBufferSize(buffersize)
		
	def __onClose(self):
		self.__sendNotifier((0,"stopped"))

	def __getService(self,streamurl):
		self.__lastStreamInfos = None
		self.__laststream = streamurl
		return eServiceReference(4097,0,streamurl)
		
	def __evUpdatedStreamInfo(self):
		service = self.session.nav.getCurrentService()
		if service is not None:
			info = service.info()
			if info is not None:
				#audio = info.getInfoString(iServiceInformation.sTagAudioCodec)
				video = info.getInfoString(iServiceInformation.sTagVideoCodec)
				if video=="":
					video=_("unknown")
				self.__lastStreamInfos = video
				
	def __StateChanged(self,val):
		if val == self.SEEK_STATE_PLAY:
			self.__sendNotifier((0,"playing"))
		elif val == self.SEEK_STATE_PAUSE:
			self.__sendNotifier((0,"paused"))
		elif val == self.SEEK_STATE_EOF:
			self.__sendNotifier((0,"stopped"))
		
	def __sendNotifier(self,val):
		for callback in PlayerNotifier:
			try:
				callback(val)
			except Exception, e:
				print "[%s] <%s> in %s"%(__name__,e,callback)
				PlayerNotifier.remove(callback)
	
	def showMovies(self):
		pass
	
	def _MoviePlayer__evPluginError(self):
		service = self.session.nav.getCurrentService()
		if service is not None:
			info = service.info()
			if info is not None:
				message = info.getInfoString(iServiceInformation.sUser+12)
				if message and message.find("text/html decoder not available")>0:
					if self.__ChoiceBoxExe:
						self.__ChoiceBoxExe.cancel()
					self.leavePlayerConfirmed((_("yes"), "quit"))
					self.__sendNotifier((1,self.__laststream))
				else:
					self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )

	def KeyExit(self):
		if self.shown:
			self.hide()
		else:
			if self.__exitmodus == 1:
				self.handleLeave()
			elif self.__exitmodus == 2:
				self.leavePlayerConfirmed((_("yes"), "quit"))
			
	def KeyStop(self):
		self.handleLeave()
		
	def ExternCommand(self,comm):
		if comm=="stop":
			if self.__ChoiceBoxExe:
				self.__ChoiceBoxExe.cancel()
			self.leavePlayerConfirmed((_("yes"), "quit"))
		elif comm=="pause":
			self.pauseService()
		elif comm=="unpause":
			self.unPauseService()
			
	def getPosition(self):
		seek = self.getSeek()
		if seek is None:
			return 0
		pos = seek.getPlayPosition()
		if pos[0]:
			return 0
		return pos[1]

	def getLength(self):
		seek = self.getSeek()
		if seek is None:
			return 0
		length = seek.getLength()
		if length[0]:
			return 0
		return length[1]
		
	def seekTo(self,pos):
		print "[%s] set position %d sec." %(__name__,pos)
		self.doSeek(pos*90000)
			
	def isPlaying(self):
		if self.seekstate == self.SEEK_STATE_PLAY:
			return True
		return False
		
	def PlayStream(self, streamurl, streamname=""):
		self["Streamname"].setText(streamname)
		if self.__ChoiceBoxExe:
			self.__ChoiceBoxExe.cancel()
		self.movieSelected(self.__getService(streamurl))
		
	def SetBufferSize(self,size):
		print "[%s] set buffersize %dk" %(__name__,size)
		self.session.nav.getCurrentService().streamed().setBufferSize(long(size) * 1024)
		
	def handleLeave(self,how="ask"):
		if how == "ask":
			menu=[(_("yes"), "quit"), (_("no"), "continue"), (_("No, but restart from begin"), "restart")]
			if self.__lastStreamInfos:
				menu.append((_("Save '%s' stream in folder '%s'?") %(self.__lastStreamInfos,self.__downloadpath), "savestream"))
			self.__ChoiceBoxExe = self.session.openWithCallback(self.__PlayerConfirmed, ChoiceBox, title=_("Stop playing this movie?"), list=menu)
		else:
			self.leavePlayerConfirmed([True, how])
			
	def __PlayerConfirmed(self, answer):
		self.__ChoiceBoxExe = None
		val = answer and answer[1]
		if val == "restart":
			self.session.nav.stopService()
			self.PlayStream(self.__laststream)
		elif val == "savestream":
			if self.__lastStreamInfos:
				from downloadScreen import DownloadScreen
				from time import time as currtime
				filename = "%d_videoplayback.mp4" %int(currtime())
				target = self.__downloadpath + filename
				self.session.open(DownloadScreen, url=self.__laststream, target=target, name=filename)
		else:
			self.leavePlayerConfirmed(answer)

#------------------------------------------------------------------------------

class ExMoviePlayer(MoviePlayer):
	def __init__(self, session, file):
		self.downloadCuesheet = self.__NewDownloadCuesheet#InfoBarCueSheetSupport
		
		MoviePlayer.__init__(self, session, self.__getService(file))
		self.skinName = "MoviePlayer"

		self["actions"] = ActionMap(["gActions", "QuickButtonActions"],
		{
			"exit": self.KeyExit,
			"stop": self.KeyStop,
			"menu": self.KeyMenu,
			"info": self.KeyInfo,
			"green_long":self.KeyGreenLong
		},-1)

		self.__show_ts_info =  cgevent.getConfig("Dmanager_show_ts_info",1)
		self.__SortBy = cgevent.getConfig("Dmanager_SortBy", SORT_NAME)
		self.__nextAutomatic=False
		self.__exitmodus = cgevent.getConfig("Dmanager_movie_exit",1)
		self.onClose.insert(0, self.__ExitPlayer)

	def KeyGreenLong(self):
		quickSelectGlobal(self,"green_long")
		
	def KeyMenu(self):
		pass
	
	def KeyInfo(self):
		if self.__lastpath[B_FILTER] & FILTER_MOVIES:
			from searchMediaInfo import BrowserFileInfos
			self.session.open(BrowserFileInfos, self.__lastpath)

	def showMovies(self):
		self.session.openWithCallback(self.__PlayNextMovie, gBrowser, setPath=self.__lastpath[B_FULL], filter=FILTER_MOVIES)
		
	def __PlayNextMovie(self, file=None):
		if file is not None:
			self.__ExitCueSheet()
			self.movieSelected(self.__getService(file))
			
	def __getService(self,file):
		service = eServiceReference(file[B_SERVICE_REF])
		self.CutsFile = service.getPath() + ".cuts"
		self.__lastpath = file
		return service
		
	def __getNextFile(self):
		self.lastdir = os_path.dirname(self.__lastpath[B_FULL])
		found=False
		for x in libgeminimain.getPyList(GETFILELIST,(self.lastdir, FILTER_MOVIES, self.__SortBy, 0, 0, self.__show_ts_info)):
			if found and (x[B_FILTER] & FILTER_MOVIES):
				return x
			if x[B_FULL] == self.__lastpath[B_FULL]:
				found=True
		return None

	def KeyExit(self):
		if self.shown:
			self.hide()
		else:
			if self.__exitmodus == 1:
				self.handleLeave("ask",True)
			elif self.__exitmodus == 2:
				self.leavePlayerConfirmed((_("yes"), "quit"))
				
	def KeyStop(self):
		self.handleLeave("ask",True)

	def handleLeave(self, how="ask", isKey=False):
		if how == "ask":
			try:
				self.__nextfile = self.__getNextFile()
				if self.__exitmodus==1 and self.__nextAutomatic==True and isKey==False and self.__nextfile is not None:
					print "[ExMoviePlayer] automatic play next movie %s" % self.__nextfile[B_NAME]
					self.__PlayNextMovie(self.__nextfile)
					return
			
				menu=[(_("yes"), "quit"),(_("no"), "continue"),("--", "--"), (_("No, but restart from begin"), "restart"), (_("Yes, and delete this movie"), "quitanddelete")]
				if self.__nextfile is not None:
					menu.append(("--", "--"))
					text = self.__nextfile[B_NAME]
					if self.__nextfile[B_FILTER] & FILTER_MOVIES:
						if self.__nextfile[B_DESC] != "":
							text = self.__nextfile[B_DESC]
					menu.append((_("No, play next Movie '%s'") % text, "nextmovie"))
					if self.__exitmodus==1:
						menu.append((_("No, always choose the next movie"), "nextautomatic"))
				self.session.openWithCallback(self.__PlayerConfirmed, ChoiceBox, title=_("Stop playing this movie?"), list=menu)
			except Exception, e:
				print "[%s] <%s>"%(__name__,e)
		else:
			self.leavePlayerConfirmed([True, how])
			
	def __PlayerConfirmed(self, answer):
		val = answer and answer[1]
		self.__nextAutomatic=False
		if val == "nextautomatic":
			self.__PlayNextMovie(self.__nextfile)
			self.__nextAutomatic=True
		elif val == "nextmovie":
			self.__PlayNextMovie(self.__nextfile)
		elif val == "restart":
			self.session.nav.stopService()
			self.__PlayNextMovie(self.__lastpath)
		else:
			self.leavePlayerConfirmed(answer)
		
	def __ExitPlayer(self):
		self.__ExitCueSheet()

#-------------thanks for the idea by cmikula, betonme---------------
	def __getCuesheet(self):
		service = self.session.nav.getCurrentService()
		if service is None:
			return None
		return service.cueSheet()

	def __ExitCueSheet(self):
		IsCue = self.__getCuesheet()
		#if IsCue:# bei TS
		#	return
		cgevent.SetCutsList(self)
	
	def __NewDownloadCuesheet(self):
		IsCue = self.__getCuesheet()
		#if IsCue:# bei TS
		#	self.cut_list = IsCue.getCutList()
		#	return
		self.cut_list = cgevent.GetCutsList(self.CutsFile)
