# -*- coding: utf-8 -*-
from gLocale import _
from WidgetVariableList import WidgetVariableList
from gTools import cleanexit, pathExists, gLoadPixmap, getXMLFile, XML_BPDESKTOP, ctoolsclass
from plugin import cgevent

from WidgetConfig import gConfigWindow, gConfigSelection, gConfigDirectory
from Components.config import config, NoSave, getConfigListEntry, ConfigText, ConfigInteger

from Screens.ChoiceBox import ChoiceBox

#-----------------------------------------------------------------------------------------------------

class BrowserFavo(WidgetVariableList):
	FAVORITENFILE = "/etc/enigma2/gemini_browserfavo.xml"
	def __init__(self, session):
		self.__newConfig=False
		WidgetVariableList.__init__ (self, session, title=_("Favourites"),  showMenuPix=True)
		self.skinName = [self.__class__.__name__+"0","VariableList2Lines_" + self.__class__.__name__,"VariableList2Lines"]
		self.onLayoutFinish.append(self.__fillListe)
		
	def __fillListe(self):
		self.hideLabel()
		list = []
		if pathExists(self.FAVORITENFILE):
			from WidgetXmlList import XML_NAME, XML_CODE, XML_ICON
			for x in getXMLFile(self, XML_BPDESKTOP, self.FAVORITENFILE):
				list.append((_(x[XML_NAME]),x[XML_CODE], gLoadPixmap(x[XML_ICON]), ctoolsclass.getSeperatorPic(), x[XML_ICON]))
		else:
			list.append((_("Movies"),"/hdd/movie", gLoadPixmap("folder_movies.png"), ctoolsclass.getSeperatorPic(), "folder_movies.png"))
			list.append((_("Media"),"/media", gLoadPixmap("folder_open.png"), ctoolsclass.getSeperatorPic(), "folder_open.png"))
			list.append((_("Root"),"/", gLoadPixmap("folder_open.png"), ctoolsclass.getSeperatorPic(), "folder_open.png"))
		self.SetList(list)
		self.SetIndex(cgevent.getConfig("Dmanager_favoindex",0))
	
	def newTitle(self):
		text = _("Favourites")
		if  self.getSwitchMode():
			text += " (" + _("Move") + ": " + _("on") + ")"
		self.SetTitle(text)
	
	def KeyMenu(self):
		menu = []
		menu.append((_("Delete"), 3))
		menu.append((_("Add"), 4))
		menu.append((_("Edit"), 5))
		menu.append(("--", ""))
		if self.getSwitchMode():
			menu.append((_("Move disable"), 1))
		else:
			menu.append((_("Move enable"), 2))
		self.session.openWithCallback(self.__menuCallback, ChoiceBox, title=_("Favourites")+ "...", list=menu)

	def __menuCallback(self, what=None):
		if what is None:
			return
		
		if what[1]==1 or what[1]==2:
			self.__newConfig=True
			self.SwitchMode()
			self.newTitle()
		elif what[1]==3:#delete
			val = self.getCurrentEntry()
			if val:
				self.__newConfig=True
				self.RemoveEntry(self.GetIndex())
		elif what[1]==4:#add
			self.session.openWithCallback(self.__Callbackadd, EditFavoEntry, (_("Name"),"/", "folder_open.png"))
		elif what[1]==5:#edit
			val = self.getCurrentEntry()
			if val:
				self.session.openWithCallback(self.__Callbackedit, EditFavoEntry, (val[0],val[1],val[4]))

	def __Callbackadd(self, val=None):
		if val:
			self.addEntry(val)
			self.__newConfig=True
			
	def __Callbackedit(self, val=None):
		if val:
			self.editEntry(self.GetIndex(),val)
			self.__newConfig=True

	def KeyOk(self):
		if self.getSwitchMode():
			self.SwitchMoveMode()
		else:
			sel = self.getCurrentEntry()
			if sel:
				cgevent.setConfig("Dmanager_favoindex",self.GetIndex())
				self.KeyExit(sel[1])
		
	def KeyExit(self, val=None):
		if self.__newConfig:
			try:
				wfile = open(self.FAVORITENFILE, 'w')
				wfile.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
				wfile.write("<xml>\n\t<BrowserFavo>\n")
				for x in self.GetList():
					wfile.write("\t\t<content>\n")
					wfile.write("\t\t\t<name><![CDATA[%s]]></name>\n" % x[0])
					wfile.write("\t\t\t<code><![CDATA[%s]]></code>\n" % x[1])
					wfile.write("\t\t\t<icon>%s</icon>\n" % x[4])
					wfile.write("\t\t</content>\n")
				wfile.write("\t</BrowserFavo>\n</xml>\n")
				wfile.close()
				print "[BrowserFavo] save XML"
			except:
				print "[BrowserFavo] error save XML"
		self.close(val)
		cleanexit(__name__)

#------------------------------------------------------------------------------------------------

class EditFavoEntry(gConfigWindow):
	def __init__(self, session, val):
		config.bp.name = NoSave(ConfigText(default=val[0], fixed_size=False))
		config.bp.path = NoSave(gConfigDirectory(default=val[1]))
		
		menu=[]
		menu.append(("folder_movies.png",_("Movies") + " (1)"))
		menu.append(("folder_movies1.png",_("Movies") + " (2)"))
		menu.append(("folder_children.png",_("Children")))
		menu.append(("folder_image.png",_("Pictures")))
		menu.append(("folder_music.png",_("Music")))
		menu.append(("folder_dvd.png","DVD"))
		menu.append(("folder_open.png",_("Path")))
		menu.append(("folder_network.png",_("Network")))
		config.bp.icon = NoSave(gConfigSelection(default=val[2], choices=menu))
		
		list=[]
		list.append(getConfigListEntry(_("Name"), config.bp.name))
		list.append(getConfigListEntry(_("Path"), config.bp.path))
		list.append(getConfigListEntry(_("Picture"), config.bp.icon))
		gConfigWindow.__init__ (self, session, list=list)
		
	def SelectionChangedNow(self):
		gConfigWindow.SelectionChangedNow(self)
		self.__newIcon()

	def KeyLeft(self):
		gConfigWindow.KeyLeft(self)
		self.__newIcon()
			
	def KeyRight(self):
		gConfigWindow.KeyRight(self)
		self.__newIcon()
		
	def __newIcon(self):
		if self.getCurrendValue() == config.bp.icon:
			self.SetIcon(config.bp.icon.value)
			
	def KeyGreen(self):
		self.close((config.bp.name.value, config.bp.path.value, gLoadPixmap(config.bp.icon.value), ctoolsclass.getSeperatorPic(), config.bp.icon.value))

	def KeyExit(self):
		self.close()
		