package model.state;

import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.UnknownHostException;

import model.GameStateManager;
import model.NetworkConnection;

public class MatchMakingState extends State {
	
	public static NetworkConnection nwc = null;
	boolean failed = false;
	boolean draw = false;
	String message = "";

	public MatchMakingState(GameStateManager gsm) {
		super("match", gsm);
	}

	@Override
	public void init() {
		if(!draw)
			return;
		
		nwc = new NetworkConnection((PlayState) gsm.getState("play"));
			try {
				nwc.connect(MenuState.name);
			} catch (UnknownHostException e) {
				failed = true;
				message = "Server is offline";
			} catch (IOException e) {
				failed = true;
				message  = "Something went wrong while trying to connect";
			}
			failed = false;
			message = "";
			
			if(!failed)
				gsm.setState("play");
	}

	@Override
	public void exit() {
		// TODO Auto-generated method stub

	}

	@Override
	public void update() {
		// TODO Auto-generated method stub

	}

	@Override
	public void paint(Graphics2D g2) {
		g2.drawString("Waiting on match", 100, 100);
		
		if(failed)
		{
			g2.drawString(message, 100, 300);
			g2.drawString("Press any key to continue", 100, 500);
		}
		
		draw = true;
		init();
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if(failed)
			gsm.setState("menu");
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

}
