""" Text Input GUI
This module presents a simple text box and blocks until
a string is entered. The prompt ("Name" in the picture) is
supplied when the ask function is called, and the user is
able to use the backspace key to edit their input.

A program to get user input, allowing backspace etc shown
in a box in the middle of the screen. Called by:
  import inputbox
  answer = inputbox.ask(screen, "Your name")

Only near the center of the screen is blitted to
"""
__author__ = "Timothy Downs"
__copyright__ = "Copyright (c) 2002 Timothy Downs"
__license__ = "Public Domain"
__version__ = "1.0"


import pygame
from pygame.locals import *


def display_box(screen, message, size=20, fgcolor=(255,255,255), bgcolor=(0,0,0)):
    "Print a message in a box in the middle of the screen"
    fontobject = pygame.font.Font(None, size)
    area = Rect(0, 0, 200, size+6)
    area.center = screen.get_rect().center
    pygame.draw.rect(screen, bgcolor, area, 0)
    pygame.draw.rect(screen, fgcolor, area, 1)
    oldclip = screen.get_clip()
    screen.set_clip(area.inflate(-4, -4))
    if len(message):
        text = fontobject.render(message, 1, fgcolor, bgcolor)
        screen.blit(text, area.move(5, 4))
    screen.set_clip(oldclip)
    pygame.display.update(area)


def ask(screen, question):
    "ask(screen, question) -> answer"
    pygame.font.init()
    current_string = ''
    display_box(screen, question + ":")
    while 1:
        event = pygame.event.wait()
        if event.type == QUIT:
            break
        if event.type != KEYDOWN:
            continue
        if event.key == K_BACKSPACE:
            current_string = current_string[:-1]
        elif event.key == K_RETURN:
            break
        elif event.unicode:
            current_string += event.unicode

        display_box(screen, question + ": " + current_string)

    return current_string

if __name__ == '__main__':
    screen = pygame.display.set_mode((320,240))
    print "'%s' was entered" % ask(screen, "Name")
