################################################################
#
#   Bell Runner - Playing Screen
#
################################################################

import os
from pygame.locals import *
from albow import Widget
from screen import BRScreen
from level_playing_view import LevelPlayingView
from game import game


class LevelTitleDisplay(Widget):

	margin = 5

	def draw(self, surf):
		name = game.level_name
		if name:
			name = os.path.basename(name)
			name = os.path.splitext(name)[0]
			if name:
				parts = name.split("-", 1)
				num = ""
				if len(parts) == 2:
					prefix, name = parts
					if prefix <> "Z":
						try:
							num = int(prefix)
						except ValueError:
							pass
				title = name.replace("_", " ")
				if num:
					title = "Church %s: %s" % (num, title)
				buf = self.font.render(title, True, self.fg_color)
				r = buf.get_rect()
				r.midleft = (self.margin, self.height // 2)
				surf.blit(buf, r)


class PlayScreen(BRScreen):

	def __init__(self, shell):
		BRScreen.__init__(self, shell)
		self.level_view = LevelPlayingView()
		info = LevelTitleDisplay(width = 500)
		r = self.level_view.rect
		info.midleft = (0, r.bottom + (self.height - r.height) // 2)
		self.add(self.level_view)
		self.add(info)
		self.level_view.focus()

	def begin_frame(self):
		game.begin_frame()
		self.invalidate()
		if game.level_is_completed():
			if game.testing:
				self.shell.edit_level()
			elif game.playing_level_set() and game.level.has_exit:
				self.shell.play_next_level()
			else:
				self.shell.show_menu_screen()

	def key_down(self, e):
		if e.cmd or K_F1 <= e.key <= K_F10:
			self.shell.menu_screen.key_down(e)
		else:
			BRScreen.key_down(self, e)
	
	def escape_key(self):
		if game.testing:
			self.shell.edit_level()
		else:
			self.shell.show_menu_screen()
