import pygame

from pygame.locals import *

from locals import *

import util

class Menu:
    logo = None
    bg= None

    def __init__(self, screen, menu, selection = 0):
        self.screen = screen

        self.title = util.bigfont.render("Päävalikko", True, COLOR1)

        if not Menu.bg:
            Menu.bg = pygame.image.load("menu/zombie-bg.jpg")


        self.menu = menu
        self.selection = selection
        self.t = 0

    def run(self):
        done = False

        while not done:
            self.screen.blit(Menu.bg, self.screen.get_rect())

            rect = self.title.get_rect()
            rect.centerx = MENUCENTER
            rect.top = MENUTOP

            #self.screen.blit(self.title, rect)

            for i in xrange(len(self.menu)):
                self.render(i)

            pygame.display.flip()

            self.t += 1

            nextframe = False
            while not nextframe:
                pygame.event.post(pygame.event.wait())
                for event in pygame.event.get():
                    if event.type == QUIT or \
                        event.type == KEYDOWN and event.key == K_ESCAPE:
                        self.selection = -1
                        done = True
                        nextframe = True
                    elif event.type == NEXTFRAME:
                        nextframe = True
                    elif event.type == JOYAXISMOTION:
                        if event.axis == 1:
                            if event.value < -0.5:
                                self.move_up()
                            if event.value > 0.5:
                                self.move_down()
                    elif event.type == JOYBUTTONDOWN:
                        if event.button == 0:
                            done = True
                    elif event.type == KEYDOWN:
                        if event.key == K_UP:
                            self.move_up()
                        elif event.key == K_DOWN:
                            self.move_down()
                        elif event.key == K_SPACE or event.key == K_RETURN:
                            done = True

        sound = pygame.mixer.Sound("sounds/menuselect.wav")
        sound.set_volume(0.5)

        sound.play()

        return self.selection

    def move_down(self):
        self.selection += 1
        if self.selection >= len(self.menu):
            self.selection = len(self.menu) - 1

    def move_up(self):
        self.selection -= 1
        if self.selection < 0:
            self.selection = 0

    def render(self, id):
        color = COLOR1
        if self.selection == id:
            color = COLOR2

        title = self.menu[id]
        image = util.bigfont.render(title, 1, color)
        rect = image.get_rect()
        rect.centerx = MENUCENTER
        rect.top = MENUTOP + 50 + id * rect.height * 1.1

        self.screen.blit(image, rect)
