from Components.config import config
from enigma import eServiceReference, eServiceCenter
import re

class PiconResolver(object):
	@staticmethod
	def getPngName(reference, nameCache, findPicon):
		if config.merlin2.skin_piconmode.value == "Name":
			ref = eServiceReference(reference)
			info = eServiceCenter.getInstance().info(ref)
			sRef = info and info.getName(ref)
			if sRef is not None:
				sRef = sRef.replace('\xc2\x86', '').replace('\xc2\x87', '')	
				sRef = re.sub('[^0-9a-zA-Z]+', '_', sRef)
				pngname = findPicon(sRef)
			else:
				pngname = ""
		else:
			x = reference.split(':')
			
			iptvname = ""
			
			if len(x) < 11: # skip invalid service references # Dr. Best --> i am doing this the dmm-way now...
				return ""
			if len(x) == 12: # some iptv channels don't have a valid service reference. use the name instead 
				iptvname = x[11]
			# streamrelay
			if x[6] == "21" and len(x) >= 11:
				pos = x[10].rfind("/")
				streamrelayref = x[10][pos+1:]
				x = streamrelayref.split("%3a")
			if len(x)>10:
				del x[x[10] and 11 or 10:] # remove name and empty path
			x[1]='0' #replace flags field
			name = '_'.join(x).strip('_')
			pngname = nameCache.get(name, "")
			if pngname == "":
				pngname = findPicon(name)
				if pngname == "":
					# lookup without path
					pngname = findPicon('_'.join(x[:10]))
					if pngname == "":
						if x[0] in ('4097', '8193'): 
							# lookup 1_* instead of 4097_*
							pngname = findPicon('1_'+'_'.join(x[1:10]))
						# DVB-T(2)
						elif int(x[0]) == 1 and (int(x[6], 16) & 0xFFFF0000) == 0xEEEE0000:
							x[6] = '{:02X}'.format(0xEEEE0000)
							pngname = findPicon('1_'+'_'.join(x[1:10]))
						if pngname == "": # no picon found. try it with the name
							pngname = findPicon(iptvname.replace(' ', '_'))
							if pngname == "": # no picon for service found
								pngname = nameCache.get("default", "")
								if pngname == "": # no default yet in cache..
									pngname = findPicon("picon_default")
									if pngname != "":
										nameCache["default"] = pngname
			if pngname != "":
				nameCache[name] = pngname
		return pngname
