import pygame
from pygame.constants import *

import time
import sys


class Menu:
	def __init__(self, game):
		self.curMenuEntry = 0
		self.menuEntries = [('start', (game.startGame, [])), ('quit', (sys.exit, []))]
		self.game = game
		self.bgcolor = (0,0,0)

		self.surface = pygame.Surface(self.game.screen.get_size())

		self.isRunning = True
		self.screensize = self.game.screen.get_size()

		self.imgMenu = pygame.image.load("menutiles.png")
		self.mtSize = (160,32)
		self.menuMapping =	{
			'start':0,
			'start_highlight':1,
			'quit':2,
			'quit_highlight':3,
			'about':4,
			'about_highlight':5,
			'highscore':6,
			'highscore_highlight':7,
		}
		self.titlePlate = pygame.image.load("titleplate.png")

		self.menu()
	
	def getMenuTile(self,nr):
		hNr = nr % 2
		vNr = nr / 2
		t = pygame.Surface(self.mtSize,pygame.SRCALPHA,32).convert_alpha()
		t.blit(self.imgMenu,(0,0),(hNr*self.mtSize[0],vNr*self.mtSize[1],self.mtSize[0],self.mtSize[1]))
		return t

	def handleMenuEvents(self):
		for event in pygame.event.get():
			if event.type == QUIT:
				self.game.gamestack.pop()
				self.isRunning = False
				return
			elif event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					self.game.gamestack.pop()
					self.isRunning = False
					return
				elif event.key == K_DOWN:
					self.curMenuEntry += 1
					if self.curMenuEntry > len(self.menuEntries) - 1:
						self.curMenuEntry = len(self.menuEntries) - 1
				elif event.key == K_UP:
					self.curMenuEntry -= 1
					if self.curMenuEntry < 0:
						self.curMenuEntry = 0
				elif event.key == K_RETURN:
					self.game.gamestack.push(*self.menuEntries[self.curMenuEntry][1])
					self.isRunning = False

	def menu(self):
		while self.isRunning:
			pygame.time.wait(100)

			self.handleMenuEvents()
			font = pygame.font.Font(None, 32)

			self.surface.fill(self.bgcolor)
			self.surface.blit(self.titlePlate,(self.screensize[0]/2-192, self.screensize[1]/2-192))
			menu_y0 = (self.screensize[1]/2)-(self.mtSize[1]+8)*(len(self.menuEntries)/2)
			menu_x0 = (self.screensize[0]/2)-(self.mtSize[0]/2)
			for i, (entry, func) in enumerate(self.menuEntries):
				if self.curMenuEntry == i: 
					entry = entry+'_highlight'
				mtile = self.getMenuTile(self.menuMapping[entry])
				self.surface.blit(mtile,(menu_x0,menu_y0+i*(self.mtSize[1]+8)))

			self.game.screen.blit(self.surface, (0,0))
			pygame.display.flip()
