import os

# 3rd party python modules.
import pygame
pygame.init()

# Own modules.
from game.classes.Preferences import *
from game.components import object_creation
from game.components import helpers
from game.classes.BG_Image import BG_Image
from game.classes.ButtonMenu import ButtonMenu
from game.components import highscore_menu
from game.components import instructions
from game.components import game
from game.components import options
from game.components import name_menu

def run( playground, clock, jukebox ):

	# Load settings first.  If the file "options.txt" is not found, it is created with default options.
	if not os.path.exists( VAR_OPTS_FILENAME ):
		helpers.init_options( VAR_OPTS_FILENAME, DEFAULT_OPTIONS )
		
	# Load settings
	settings = helpers.load_options( VAR_OPTS_FILENAME )

	# Decide whether to play music in the beginning of the game or not.
	if settings["music"] == "NO":
		# Do not play any music.
		jukebox.turn_off()

	# Decide whether to play sounds in the beginning of the game or not.
	if settings["sounds"] == "NO":
		sound_channel.set_volume( 0 )

	# Set up the labels.
	labels = object_creation.create_labels( MAIN_MENU["labels"] )
	# Set up a few buttons.
	buttons = object_creation.create_buttons( MAIN_MENU["buttons"] )

	# Set up the menu itself.
	menu1 = ButtonMenu( buttons, 1 )

	# Load the background image.
	bg_image = BG_Image( BG_IMAGE_FILENAME, ( SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 ), 50 )
	
	for b in menu1.buttons:
		if b._unique_name == "btn_name":
			b.set_text( settings["name"] )

	running = True
	while running:
		events = pygame.event.get()
		if helpers.user_quit( events ):
			return False		
		playground.fill( WHITE )

		# Update buttons
		choice = menu1.update( events )
		
		if choice == "start_game":
			game.run( playground, clock, jukebox )
		elif choice == "show_options":
			options.run( playground, clock, jukebox )
		elif choice == "show_highscores":
			highscore_menu.run( playground, clock, jukebox )
		elif choice == "show_instructions":
			instructions.run( playground, clock, jukebox )
		elif choice == "show_credits":
			credits.run()
		elif choice == "name_change":
			name_menu.run( playground, clock, jukebox )
			for b in buttons:
				if b._unique_name == "btn_name":
					b.set_text( helpers.load_options( VAR_OPTS_FILENAME )["name"] )
		elif choice == "exit_game":
			running = False
			

		# Blit the background image.
		playground.blit( bg_image.image, bg_image.rect )

		# Draw labels.
		labels.draw( playground )
		# Draw buttons.
		menu1.draw( playground )
		
		pygame.display.update()
		clock.tick( FPS )
		
		# Music still playing?
		jukebox.still_playing()		
