# -*- coding: utf-8 -*-
from gTools import gLoadPixmap, getXMLFile, XML_MENU, pathExists

class MenuXMLlist:
	#XML-Eintraege
	GOUP = 0
	MENU = 1
	ENTRY = 2
	#GoUpListe
	LISTE = 0
	INDEX = 1
	TITLE = 2

	def __init__(self, file="", title="", extension="", sort=True):
		self.GoUp_List = []
		self.sort = sort
		self.extensionPic = "ext_unknown.png"
		self.level = 0
		if extension != "":
			self.extensionPic = extension
		
		if pathExists(file):
			self.GoUp_List.append([getXMLFile(self, XML_MENU, file), 0, title])
			self.fillList()
	
	def fillList(self):
		slist = []
		if self.level > 0:
			slist.append(("..", gLoadPixmap("ext_back.png"), MenuXMLlist.GOUP))

		for a in self.GoUp_List[self.level][MenuXMLlist.LISTE]:
			if isinstance(a, tuple):
				slist.append((a[0], gLoadPixmap(self.extensionPic), MenuXMLlist.ENTRY, a))
			elif isinstance(a, list):
				if isinstance(a[0], str):
					slist.append((a[0], gLoadPixmap("ext_folder.png"), MenuXMLlist.MENU, a))
				else:
					for b in a:
						if isinstance(b, tuple):
							slist.append((b[0], gLoadPixmap(self.extensionPic), MenuXMLlist.ENTRY, b))

		if self.sort:
			slist = sorted(slist, key=lambda x: x[2], reverse=False)
		self.SetList(slist)
		self.SetIndex(self.GoUp_List[self.level][MenuXMLlist.INDEX])
		
	def pressOK(self):
		sel = self.getCurrentEntry()
		if sel:
			if sel[2] == MenuXMLlist.MENU:
				text = ""
				if self.level>0:
					text += self.GoUp_List[self.level][MenuXMLlist.TITLE] + " / "
				text += sel[3][0]
				# Neue Liste erstellen, ersten Eintrag abschneiden
				list = []
				list.extend(sel[3])
				list.pop(0)
				self.GoUp_List[self.level][1] = self.GetIndex() #letzten Index ermitteln
				self.GoUp_List.append([list,0, text]) #Werte in die Goupliste eintragen
				self.level += 1
				self.fillList()
				return text
			elif sel[2] == MenuXMLlist.GOUP:
				self.level -= 1
				self.GoUp_List.pop()
				self.fillList()
				return self.GoUp_List[self.level][MenuXMLlist.TITLE]
			if sel[2] == MenuXMLlist.ENTRY:
				return sel[3]
		return None
	
	def sel_changed(self):
		if sel is None:
			return None
		sel = self.getCurrentEntry()
		if sel and sel[2] == MenuXMLlist.ENTRY:
			return sel[3]
		return None
