from __future__ import division
from Components.Converter.Converter import Converter
from Components.Element import cached, ElementError
from enigma import iServiceInformation
from ServiceReference import ServiceReference
from os import stat as os_stat, path as os_path
from stat import ST_SIZE as stat_ST_SIZE

class MovieInfo(Converter, object):
	MOVIE_SHORT_DESCRIPTION = 0 # meta description when available.. when not .eit short description
	MOVIE_META_DESCRIPTION = 1 # just meta description when available
	MOVIE_REC_SERVICE_NAME = 2 # name of recording service
	MOVIE_REC_FILESIZE = 3 # filesize of recording

	def __init__(self, type):
		if type == "ShortDescription":
			self.type = self.MOVIE_SHORT_DESCRIPTION
		elif type == "MetaDescription":
			self.type = self.MOVIE_META_DESCRIPTION
		elif type == "RecordServiceName":
			self.type = self.MOVIE_REC_SERVICE_NAME
		elif type == "FileSize":
			self.type = self.MOVIE_REC_FILESIZE
		else:
			raise ElementError("'%s' is not <ShortDescription|MetaDescription|RecordServiceName|FileSize> for MovieInfo converter" % type)
		Converter.__init__(self, type)

	@cached
	def getText(self):
		service = self.source.service
		info = self.source.info
		if info and service:
			if self.type == self.MOVIE_SHORT_DESCRIPTION:
				event = self.source.event
				if event:
					descr = info.getInfoString(service, iServiceInformation.sDescription)
					if descr == "":
						return event.getShortDescription()
					else:
						return descr
			elif self.type == self.MOVIE_META_DESCRIPTION:
				descr = info.getInfoString(service, iServiceInformation.sDescription)
				if descr == "":
					descr = self.source.merlinMetaData and self.source.merlinMetaData.getDescription()
					if not descr and self.source.event:
						descr = self.source.event.getShortDescription()
				return descr
			elif self.type == self.MOVIE_REC_SERVICE_NAME:
				rec_ref_str = info.getInfoString(service, iServiceInformation.sServiceref)
				if rec_ref_str == "" and self.source.merlinMetaData:
					rec_ref_str = self.source.merlinMetaData.getServiceReference()
				return ServiceReference(rec_ref_str).getServiceName()
			elif self.type == self.MOVIE_REC_FILESIZE:
				filesize = info.getInfoObject(service, iServiceInformation.sFileSize)
				if filesize is None and self.source.merlinMetaData:
					filesize = self.source.merlinMetaData.getFilesize()
				if filesize is not None:
					filesize = filesize / (1024*1024.0)
					if filesize >= 1024:
						return "%.2f GB" %(filesize / 1024.0)
					return "%.2f MB" % (filesize)
				else:
					if service.getPath():
						try:
							fileInfo = os_stat(os_path.realpath(service.getPath()))
							filesize = fileInfo[stat_ST_SIZE]
							filesize = filesize / (1024*1024.0)
							if filesize >= 1024:
								return "%.2f GB" %(filesize / 1024.0)
							return "%.2f MB" % (filesize)
						except: pass
		return ""

	text = property(getText)
