# Nick Maggini
# login.py
# This opens a text box for a user to input a login name
import pygame
import pygame.draw
import pygame.event
import pygame.font
from pygame.locals import *

WHITE = (235, 235, 250)
BLACK = (0, 0, 0)

WIDTH = 500
HEIGHT = 400

# The max length of an username
LENGTH = 10
1

# Gets and returns the key pressed, while waiting for key, it will quit if requested
def get_key():

    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # If quit event, end game
                running = False
            if event.type == KEYDOWN:
                return event.key

    return False  # Should only be hit on quit


# Draws a text box with what the user typed in
def display_box(screen, message):

    display = pygame.display.set_mode((WIDTH, HEIGHT))
    display.fill(WHITE)

    # Default font
    font = pygame.font.Font(None, 18)

    # Text box
    pygame.draw.rect(screen, BLACK, ((WIDTH / 2) - 102, (HEIGHT / 2) - 15, 200, 25), 1)

    # If there is a message print it
    if len(message) != 0:
        screen.blit(font.render(message, 1, BLACK), ((WIDTH / 2) - 100, (HEIGHT / 2) - 10))

    pygame.display.update()


# Get and return user imputed name
def get_name(display, label):

    pygame.font.init()
    current_string = []
    # Draw the text, join the label and current string list
    display_box(display, label + ": " + ''.join(current_string))

    while True:
        key = get_key()
        if key:
            if key == K_BACKSPACE:  # Allows for working backspace
                current_string = current_string[0:-1]
            elif key == K_RETURN:  # Enter was hit, break and return name
                break
            elif key == K_MINUS:  # Underscores allowed
                current_string.append("_")
            elif len(current_string) < LENGTH:  # Cap the username at length
                if key <= 127:  # Prevent unwanted chars
                    current_string.append(chr(key))
        else:  # Key was returned False, time to quit
            print("Exiting Game from Login")
            pygame.quit()
            quit()

        # Draw the text, join the label and current string list
        display_box(display, label + ": " + ''.join(current_string))

    return ''.join(current_string)


def start():
    display = pygame.display.set_mode((WIDTH, HEIGHT))
    name = get_name(display, "Name")
    password = get_name(display, "Password")
    return name, password
