import java.util.HashMap;

/**
 * Server für das WORDLE Spiel.
 */
public class WordleServer extends Server {

	public static final int DEFAULT_PORT = 1000;

	public static void main(String[] args) {
		new WordleServer();
	}

	private DatabaseConnector db;

	private HashMap<String, User> users;
	private Query query;

	public WordleServer() {
		this(DEFAULT_PORT);
	}

	public WordleServer(int pPort) {
		super(pPort);
		query = new Query();
		db = new DatabaseConnector("", 0, "wordle.db", "", "");
		users = new HashMap<>();
	}

	@Override
	public void processNewConnection(String pClientIP, int pClientPort) {
		String connectionID = pClientIP + ":" + Integer.toString(pClientPort);
		User u = new User(connectionID);
		users.put(connectionID, u);
		send(pClientIP, pClientPort, "+OK Verbindung zum Wordle Server erfolgreich aufgebaut");
		u.setState(1);

	}

	@Override
	public void processClosingConnection(String pClientIP, int pClientPort) {

	}

	@Override
	public void processMessage(String pClientIP, int pClientPort, String pMessage) {
		String connectionID = pClientIP + ":" + Integer.toString(pClientPort);
		User u = users.get(connectionID);
		u.setConnectionID(connectionID);

		if (pMessage.equals("QUIT")) {
			send(pClientIP, pClientPort, "+OK Bye");
			close();
		}

		switch (u.getState()) {
		case 1:
			// Anmeldephase
			String m = pMessage.substring(0, 3);
			if (m.equalsIgnoreCase("USER")) {
				m = pMessage.substring(6, pMessage.length() - 1);
				u.setUsername(m);
				send(pClientIP, pClientPort, "+OK");
			} else if (m.equalsIgnoreCase("PASS")) {
				m = pMessage.substring(6, pMessage.length() - 1);
				u.setPassword(m);
				if (u.getPassword() != null && u.getUsername() != null) {
					if (query.checkLogin(u.getUsername(), u.getPassword())) {
						send(pClientIP, pClientPort, "+OK welcome");
						u.setState(3);
					} else {
						send(pClientIP, pClientPort, "+ERR login not valid");
					}
				}
			} else {
				send(pClientIP, pClientPort, "-ERR Command not valid in this state");
			}
			break;
		case 2:
			// Spielphase
			break;
		case 3:
			// Zwischenphase(Angemeldet)
			break;

		}
	}

}
