import os, sys, string
from xml.dom import minidom, Node
import pygame
from pygame.locals import *
from main import *
from options import *
from functions import drawText, resetSurface
#from menufunctions import *

options = Options()
#options.loadFromXML("options.xml")

class Item:
	def __init__(self,id,text,image=None):
		self.id = id
		self.image = image
		self.text = text
		self.loadImage()
		
	def loadImage(self):
		fullname = os.path.join('menu', self.image)
		image = None
		try:
			image = pygame.image.load(fullname)
			image = image.convert()
		except pygame.error, message:
			print 'Nie udalo sie zaladowac obrazka:', fullname
#			raise SystemExit, message
		self.image = image
		
	def onUse(self):
		print "Item",self.id,"is used."
		
class Menu(Item):
	def __init__(self,id,text,image,parent=None):
		Item.__init__(self,id,text,image)
		self.parent = parent
		self.items = []
		self.actions = []
		self.currentitem = 0
		self.lastscore = None
		
	def addItem(self,item,action):
		self.items.append(item)
		self.actions.append(action)
		
	def changeCurrentItem(self,x):
		self.currentitem += x
		if (self.currentitem >= self.itemCount()):
			self.currentitem = 0
		if (self.currentitem < 0):
			self.currentitem = self.itemCount()-1
			
	def drawMenu(self, surface):
		def calcSum(self, sep, size, scoresize):
			if (self.image != None):
				sum = self.image.get_height()
			else:
				sum = size
			for it in self.items:
				if (it.image != None):
					sum += sep + it.image.get_height()
				else:
					sum += sep + size
			sum += sep + scoresize #last score
			return sum
		sep = 100
		size = 36
		scoresize = 20
		width, height = surface.get_width(), surface.get_height()
		midw = width/2
		midh = height/2
		gritems = []
		if (self.id!="hiscores"):
			num = self.itemCount()+2
			sum = calcSum(self, sep, size, scoresize)
			starty = (height - sum)/2
			#while (starty < size/2):
			while (starty < (height-sum-starty)):
				sep -= 1
				sum = calcSum(self, sep, size, scoresize)
				starty = (height - sum)/2
			if (self.image != None):
				gritems.append((self.image, self.image.get_rect(center=(midw,starty))))
			else:
				gritems.append(drawText(self.text,(50,150,50),(255,255,255),(midw,starty)))
			for i in range(1,num-1):
				if (i-1==self.currentitem):
					if (self.items[i-1].image != None):
	#					w = self.items[i-1].image.get_width() + 10
	#					h = self.items[i-1].image.get_height() + 10
	#					tmpsrf = pygame.Surface((w,h))
	#					tmpsrf.fill((240,240,20))
	#					tmpsrf.blit(self.items[i-1].image,(w/2,h/2))
	#					tmpsrf = self.items[i-1].image.convert(pygame.Surface((w+5, h+5)))
						tmpsrf = pygame.transform.rotozoom(self.items[i-1].image, 0, 1.2)
						gritems.append((tmpsrf, tmpsrf.get_rect(center=(midw,starty+i*(size/2+sep)))))
					else:
						if (self.actions[i-1][0] == "setparam"):
							val = options.getParam(self.actions[i-1][1])
							gritems.append(drawText(self.items[i-1].text+"   "+str(val),(255,12,42),(255,255,255),(midw,starty+i*(size/2+sep))))
						else:
							gritems.append(drawText(self.items[i-1].text,(255,12,42),(255,255,255),(midw,starty+i*(size/2+sep))))
				else:
					if (self.items[i-1].image != None):
						gritems.append((self.items[i-1].image, self.items[i-1].image.get_rect(center=(midw,starty+i*(size/2+sep)))))
					else:
						if (self.actions[i-1][0] == "setparam"):
							val = options.getParam(self.actions[i-1][1])
							gritems.append(drawText(self.items[i-1].text+"   "+str(val),(35,12,42),(255,255,255),(midw,starty+i*(size/2+sep))))
						else:
							gritems.append(drawText(self.items[i-1].text,(35,12,42),(255,255,255),(midw,starty+i*(size/2+sep))))
			if (self.lastscore != None):
				text = "Last score: "+str(self.lastscore[0])+" points, "
				text += str(self.lastscore[1])+" kills, max kombo x"+str(self.lastscore[2])
				gritems.append(drawText2(text,scoresize,(70,150,100),(255,255,255),(midw,starty+(num-1)*(size/2+sep))))
		else:
			num = 12
			sep = height/20.0
			size = height/20.0
			sum = calcSum(self, sep, size, 0)
			sum += 10*(sep+size)-6*sep
			starty = (height - sum)/2
			if (self.image != None):
				gritems.append((self.image, self.image.get_rect(center=(midw,starty))))
				next = self.image.get_height()/2.0+sep
			else:
				gritems.append(drawText(self.text,(50,150,50),(255,255,255),(midw,starty)))
				next = size/2+sep
			for i in range(10):
				score = options.hiscores.scores[i]
				scrtxt = str(i+1)+". "+str(score[0])+" points, "+str(score[1])+" kills, max kombo x"+str(score[2])
				gritems.append(drawText2(scrtxt,size,(35,12,42),(255,255,255),(midw,starty+next)))
				next += size/2+sep
			if (self.items[0].image != None):
				tmpsrf = pygame.transform.rotozoom(self.items[0].image, 0, 1.2)
				gritems.append((tmpsrf, tmpsrf.get_rect(center=(midw,starty+next))))
			else:
				gritems.append(drawText(self.items[0].text,(255,12,42),(255,255,255),(midw,starty+next)))
				
		resetSurface(surface,(255,255,255))		
		for elem in gritems:
			surface.blit(elem[0],elem[1])
			
	def getCurrentAction(self):
		return self.actions[self.currentitem]
			
	def getCurrentItem(self):
		return self.items[self.currentitem]
		
	def hasItem(self,item):
		if item in self.items:
			return True
		else:
			return False
			
	def itemCount(self):
		return len(self.items)
		
	def write(self):
		i = 0
		for item in self.items:
			print "Item "+str(i)+": ",item.id
			i += 1
			
class WholeMenu:
	def __init__(self):
		self.menus = []
		self.currentmenu = 0
		self.playing = False
		self.hiscores = HiScores()
#		if (os.path.exists(os.path.join(getConfigDir(),"hiscores"))):
#			self.hiscores.load()
#		else:
#			self.hiscores.loadFromXML("hiscores")
#		self.hiscores.save()
		
	def __getitem__(self,i):
		if (type(i) == int):
			return self.menus[i]
		if (type(i) == str):
			for menu in self.menus:
				if menu.id == i:
					return menu
		
	def append(self, menu):
		self.menus.append(menu)
		
	def childCount(self, menuname):
		count = 0
		for menu in self.menus:
			if menu.parent == menuname:
				count += 1
		return count
		
	def getChildren(self, menuname):
		children = WholeMenu()
		for menu in self.menus:
			if menu.parent == menuname:
				children.append(menu)
		return children
		
	def getCurrentMenu(self):
		return self.menus[self.currentmenu]
		
	def getItems(self, menuname):
		return self[menuname].items
		
	def getMenu(self, menuname):
		for menu in self.menus:
			if menu.id == menuname:
				return menu
		return None
		
	def getMenuNumber(self, menuname):
		for i in range(len(self.menus)):
			if (self.menus[i].id == menuname):
				return i
		return -1
		
	def itemCount(self, menuname):
		return self[menuname].itemCount()
		
	def loadFromXML(self, filename):
		dok = minidom.parse(filename)
		xmlmenus = dok.getElementsByTagName('menu')
		for elem in xmlmenus:
			id, action, text, image, parent = None, None, None, None, None
			items = []
			if "id" in elem.attributes.keys():
				id = elem.attributes["id"].value
			if "parent" in elem.attributes.keys():
				parent = elem.attributes["parent"].value
			items = elem.getElementsByTagName('item')
			text = elem.getElementsByTagName("text")[0].childNodes[0].nodeValue
			image = elem.getElementsByTagName("image")[0].childNodes[0].nodeValue
			self.append(Menu(id,text,image,parent))
			for item in items:
				action = []
				if "id" in item.attributes.keys():
					idd = item.attributes["id"].value
				if "action" in item.attributes.keys():
					action.append(item.attributes["action"].value)
				if "param" in item.attributes.keys():
					action.append(item.attributes["param"].value)
				txt = item.getElementsByTagName("text")[0].childNodes[0].nodeValue
				img = item.getElementsByTagName("image")[0].childNodes[0].nodeValue
				self.menus[-1].items.append(Item(idd,txt,img))
				self.menus[-1].actions.append(action)
				
#	def loadOptions(self,filename):
#		self.options.loadFromXML(filename)
				
	def runAction(self, surface):
		curmenu = self.getCurrentMenu()
		act = curmenu.getCurrentAction()
		if (act[0] == "submenu"):
			surface.fill((255,255,255))
			self.currentmenu = self.getMenuNumber(curmenu.getCurrentItem().id)
		elif (act[0] == "hiscores"):
			surface.fill((255,255,255))
			self.currentmenu = self.getMenuNumber(curmenu.getCurrentItem().id)
		elif (act[0] == "parentmenu"):
			surface.fill((255,255,255))
			self.currentmenu = self.getMenuNumber(curmenu.parent)
			options.save()
		elif (act[0] == "setparam"):
			pass
#			param = act[1]
#			print param
#			val = self.options.getParam(param)
#			for event in pygame.event.get():
#				if event.type == KEYDOWN: 
#					if event.key == K_LEFT:
#						val -= 1
#					elif event.key == K_RIGHT:
#						val += 1
#			print val
		elif (act[0] == "startGame"):
			return eval(act[0]+"()")
		else:
			exec(act[0]+"()")
			
	def setLastScore(self,score):
		for menu in self.menus:
			menu.lastscore = score

	def setParam(self,val):
		curmenu = self.getCurrentMenu()
		act = curmenu.getCurrentAction()
		if (act[0] == "setparam"):
			param = act[1]
			curval = options.getParam(param)
			options.setParam(param,curval+val)
		
	def write(self):
		menustmp = self.menus
		for menu in menustmp:
			ch = self.getChildren(menu.id)
			it = self.getItems(menu.id)
			i = 0
			for item in it:
				if item.id in ch.menus.id:
					pass
			#~ print "Menu: ",menu.id,self.childCount(menu.id)
			#~ menu.write()
		

#~ menu2 = WholeMenu()
#~ menu2.loadFromXML("test.xml")
#~ menu2.write()
#~ print menu2.itemCount("main")



		
