package model.state;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.util.Arrays;

import model.GameStateManager;
import resources.image.Images;
import resources.image.Images.ImageType;

public class MenuState extends State {

	// Create random username on start
	public static String name = "Guest" + Math.round((Math.random() * 1000));

	// Disallow certain characters in name
	private static int[] not_allowed = { KeyEvent.VK_COMMA, KeyEvent.VK_SEMICOLON, KeyEvent.VK_PERIOD, KeyEvent.VK_QUOTE, KeyEvent.VK_QUOTEDBL, KeyEvent.VK_SHIFT };

	// This is the menu state, it is the default state when the game starts
	public MenuState(GameStateManager gsm) {
		super("menu", gsm);
	}

	/* INIT AND EXIT */
	@Override
	public void init() {

	}

	@Override
	public void exit() {
	}

	/* UPDATE */
	@Override
	public void update() {

	}

	@Override
	public void paint(Graphics2D g2) {
		g2.drawImage(Images.getImage(ImageType.BACKGROUND_MENU), 0, 0, null);
		g2.drawImage(Images.getImage(ImageType.PLAYER1).getSubimage(38, 0, 40, 54), 610, 550, null);
		g2.drawImage(Images.getImage(ImageType.PLAYER2).getSubimage(38, 0, 40, 54), 670, 550, null);

		g2.setColor(Color.WHITE);

		g2.setFont(new Font("Segoe UI", Font.PLAIN, 20));
		g2.drawString("Type your name and press ENTER to start the game", 20, 690);

		g2.setFont(new Font("Segoe UI", Font.BOLD, 30));
		g2.drawString(name.toString(), 20, 730);
		g2.drawRect(15, 702, 380, 36);

		g2.setFont(new Font("Segoe UI", Font.BOLD, 80));
		g2.drawString("Bubble Trouble", 100, 150);
	}

	/* EVENTS */
	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			// Start the game
			gsm.setState("play");
		}

		if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && name.length() > 0) {
			// Remove last letter from name when BACKSPACE is pressed
			name = name.substring(0, name.length() - 1);
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (name.length() <= 15 && e.getKeyCode() != KeyEvent.VK_BACK_SPACE && !Arrays.asList(not_allowed).contains(e.getKeyCode())) {
			// Add allowed characters to name
			name += e.getKeyChar();
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
	}
}
