from __future__ import print_function
# Cover renderer
# 
# Coded by dre (c) 2014 - 2018
# Support: board.dreambox.tools
# E-Mail: dre@dreambox.tools
#
# This renderer is open source but it is NOT free software.
#
# This renderer may only be distributed to and executed on hardware which
# is licensed by Dream Multimedia GmbH.
# In other words:
# It's NOT allowed to distribute any parts of this renderer or its source code in ANY way
# to hardware which is NOT licensed by Dream Multimedia GmbH.
# It's NOT allowed to execute this renderer and its source code or even parts of it in ANY way
# on hardware which is NOT licensed by Dream Multimedia GmbH.
#
# If you want to use or modify the code or parts of it,	 
# you have to keep MY license and inform me about the modifications by mail.

from Renderer import Renderer
from enigma import ePixmap, eEnv
from Tools.Directories import fileExists, SCOPE_SKIN_IMAGE, SCOPE_CURRENT_SKIN, resolveFilename
from Components.config import config
from os import listdir as os_listdir, path as os_path
if fileExists("/usr/lib/enigma2/python/Plugins/Extensions/ExternalMovieInfoLoader/plugin.pyo"):
	from Plugins.Extensions.ExternalMovieInfoLoader.plugin import getCoverPathConfig
	hasEMIL = True
else:
	hasEMIL = False


class Cover(Renderer):
	searchPaths = (eEnv.resolve('${datadir}/enigma2/cover/'),
				'/media/cf/cover/',
				'/media/usb/cover/',
				'/media/sdcard/cover/',
				'/data/cover/',)	
	
	if os_path.ismount('/dreambox-data'):
		searchPaths = searchPaths + ("/dreambox-data/cover/",)			
	# 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) + "/cover/",)	
	
	def __init__(self):
		Renderer.__init__(self)
		self.useCurrentDir = False
		if hasEMIL:
			self.useCurrentDir = getCoverPathConfig() == "directory of movie"
		self.nameCache = {}
		self.jpgname = ""
		
	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 changed(self, what):
		if self.instance and config.merlin2.showcoverinmovielist.value:
			jpgname = ""
			if what[0] != self.CHANGED_CLEAR:
				moviename = self.source.text
				
				jpgname = self.nameCache.get(moviename, "")
				if jpgname == "":
					jpgname = self.findCover(moviename)
					if jpgname != "":
						self.nameCache[moviename] = jpgname
			if jpgname == "": # no cover for movie found
				jpgname = self.nameCache.get("default", "")
				if jpgname == "": # no default yet in cache..
					jpgname = self.findCover("cover_default")
					if jpgname == "":
						tmp = resolveFilename(SCOPE_CURRENT_SKIN, "cover_default.png")
						if fileExists(tmp):
							jpgname = tmp
						else:
							tmp = resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/cover_default.png")
							if fileExists(tmp):
								jpgname = tmp
					if jpgname != "":
						self.nameCache["default"] = jpgname
					else:
						jpgname = ""
			if self.jpgname != jpgname:
				if jpgname == "":
					self.instance.hide()
				else:
					self.instance.setPixmapFromFile(jpgname)
					self.instance.show()
				self.jpgname = jpgname
		elif self.instance and config.merlin2.showcoverinmovielist.value == False:
			self.instance.hide()
		elif self.instance is None:
			print("instance is none")
				
	def findCover(self, moviename):
		filetype = ".jpg"
		if hasEMIL and self.useCurrentDir:
			currentDir = self.source.getMoviePath()
			if not currentDir == "":
				currentDir = currentDir + "/"
			if not currentDir in self.searchPaths and currentDir != "":
				self.searchPaths = self.searchPaths + (currentDir,)
		for path in self.searchPaths:
			if moviename == "cover_default" or moviename == "default" or moviename == "folder":
				filetype = ".png"
			jpgname = (path) + moviename + filetype
			if fileExists(jpgname):
				return jpgname
		return ""
				