from Components.Merlin import MerlinImage
from enigma import eServiceCenter, eServiceReference, iServiceInformation
from os import path as os_path
from re import compile
from merlin.emerlin import eMerlin

tvshow_regex = compile('^((?P<ShowName>.*[^ (_.-])[ (_.-]+([S|s](?P<SeasonA>\d{1,2})[E|e](?P<EpisodeA>\d{1,2})|(?<!\d{4}[ (_.])[S|s]eason[. _-]+(?P<SeasonC>\d{1,2})[/. _-]+[E|e]pisode[. _-]+(?P<EpisodeC>\d{1,2})|(?P<SeasonD>\d+)[X|x](?P<EpisodeD>\d+)))|(([S|s](?P<SeasonStupidA>\d{1,2})[E|e](?P<EpisodeStupidA>\d{1,2})|(?P<SeasonStupidB>\d+)[X|x](?P<EpisodeStupidB>\d+))[. _-]+((?P<StupidShowName>.+?)((?<![._-])-(?P<rest>[^-]+))?)?$)')


class ExternalMovieInfo(object):

	@staticmethod
	def generateFilename(serviceref, coverpath, file_extension):
		basename = os_path.splitext(os_path.basename(serviceref.getPath()))[0] + file_extension
		if coverpath == "directory of movie":
			dirname = os_path.dirname(serviceref.getPath())
		else:
			dirname = coverpath
		extension = serviceref.getPath().split('.')[-1].lower()
		if extension in MerlinImage.getExtensions():
			metaData = eMerlin.getInstance().parseMeta(serviceref.getPath())
			if metaData:
				meta_name = metaData.getName()
				if meta_name != "":
					tvshow = tvshow_regex.match(meta_name)
					if tvshow is not None:
						basename = ExternalMovieInfo.checkFilename(tvshow.groupdict()['ShowName'] if tvshow.groupdict()['ShowName'] else tvshow.groupdict()['StupidShowName']) + file_extension
					else:
						basename = ExternalMovieInfo.checkFilename(meta_name) + file_extension
			else:
				tvshow = tvshow_regex.match(basename)
				if tvshow is not None:
					basename = ExternalMovieInfo.checkFilename(tvshow.groupdict()['ShowName'] if tvshow.groupdict()['ShowName'] else tvshow.groupdict()['StupidShowName']) + file_extension
		else:
			serviceHandler = eServiceCenter.getInstance()
			info = serviceHandler.info(serviceref)
			if info:
				meta_name = info.getName(serviceref)
				tvshow = tvshow_regex.match(meta_name)
				if tvshow is not None:
					meta_name = tvshow.groupdict()['ShowName'] if tvshow.groupdict()['ShowName'] else tvshow.groupdict()['StupidShowName']
				elif meta_name.endswith(".ts"): # no meta available
					meta_name = os_path.splitext(os_path.basename(meta_name))[0]
				basename = ExternalMovieInfo.checkFilename(meta_name) + file_extension
		try:
			return os_path.join(dirname, basename).encode('utf-8')
		except:
			return os_path.join(dirname, basename)
	
	@staticmethod	
	def checkFilename(filename):
		for invalid in '*<>\+:=/";[]|':
			filename = filename.replace(invalid,'_')
		return filename
