##
## Picon renderer by Gruffy .. some speedups by Ghost
##
from Renderer import Renderer
from enigma import ePixmap, eEnv, gPixmapPtr
from Tools.Directories import fileExists, SCOPE_SKIN_IMAGE, SCOPE_CURRENT_SKIN, resolveFilename
from Tools.PiconResolver import PiconResolver
from Components.config import config
from os import listdir as os_listdir, path as os_path

import xml.etree.cElementTree

class Picon(Renderer):
	searchPaths = ('/data/%s/', eEnv.resolve('${datadir}/enigma2/%s/'),
				'/media/cf/%s/',
				'/media/usb/%s/',
				'/media/sdcard/%s/',)	
	
	if os_path.ismount('/dreambox-data'):
		searchPaths = searchPaths + ("/dreambox-data/%s/",)			
	# add mounts to searchPaths (mounted at boot time only!)	
	blockList = ["hdd","cf","usb","sdcard"]
	dirList = os_listdir("/media")
	
	if fileExists("/proc/mounts"):
		mountsFile = open("/proc/mounts" ,"r")
		for line in mountsFile:
			entry = line.split()
			if entry[2] in ["nfs", "nfs4", "smbfs", "cifs"]:
				if entry[1].startswith("/media/"):
					blockList.append(entry[1][7:])
		mountsFile.close()	
		
	for dir in dirList:
		if dir in blockList:
			continue
		if os_path.ismount("/media/%s" %(dir)) or (os_path.islink("/media/%s" %(dir)) and os_path.ismount(os_path.realpath("/media/%s" %(dir)))):
			searchPaths = searchPaths + ("/media/%s" %(dir) + "/%s/",)	

	def __init__(self):
		Renderer.__init__(self)
		self.path = "picon"
		self.nameCache = { }
		self.pngname = ""
		self.enabled = False
		self.setActivation()

	def setActivation(self):
		config.merlin2.skin_showpicon.addNotifier(self.setConfigActivation, initial_call = True)

	def setConfigActivation(self, configElement):
		self.enabled = configElement.value

	def applySkin(self, desktop, parent):
		attribs = [ ]
		for (attrib, value) in self.skinAttributes:
			if attrib == "path":
				self.path = value
			else:
				attribs.append((attrib,value))
		self.skinAttributes = attribs
		return Renderer.applySkin(self, desktop, parent)

	GUI_WIDGET = ePixmap

	def postWidgetCreate(self, instance):
		instance.setScale(1)
		instance.setDefaultAnimationEnabled(self.source.isAnimated)

	def changed(self, what):
		#dre
		if self.instance and self.enabled:
		#if self.instance:
			if what[0] == self.CHANGED_ANIMATED:
				self.instance.setDefaultAnimationEnabled(self.source.isAnimated)
				return
			pngname = ""
			sname = self.source.text
			if what[0] != self.CHANGED_CLEAR:
				pngname = PiconResolver.getPngName(sname, self.nameCache, self.findPicon)
			if pngname == "": # no picon for service found, resolve skin default picon
				tmp = resolveFilename(SCOPE_CURRENT_SKIN, "picon_default.png")
				if fileExists(tmp):
					pngname = tmp
				else:
					pngname = resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/picon_default.png")
				self.nameCache["default"] = pngname

			if self.pngname != pngname:
				self.instance.setPixmapFromFile(pngname)
				self.pngname = pngname
		elif self.instance and not self.enabled:
			self.instance.setPixmap(gPixmapPtr())

	def findPicon(self, serviceName):
		mappedServiceName = None
		if fileExists("/etc/enigma2/piconmapper.xml"):
			mappedServiceName = self.getPiconMapping(serviceName)
					
		for path in self.searchPaths:
			if not mappedServiceName is None:
				pngname = (path % self.path) + mappedServiceName + ".png"
				if fileExists(pngname):
					return pngname
			pngname = (path % self.path) + serviceName + ".png"
			if fileExists(pngname):
				return pngname
		return ""
		
	def getPiconMapping(self, serviceName):
		
		piconmapper = file("/etc/enigma2/piconmapper.xml")
		
		piconmapperdom = xml.etree.cElementTree.parse(piconmapper)
		
		piconmapper.close()
		
		xmldata = piconmapperdom.getroot()
		
		for x in xmldata.findall('piconmapping'):
			if x.get('sref') == serviceName:
				return x.get('picon')
		
		return None
