import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Game {

	private static final int LOGIN_PHASE = 0;
	private static final int GAME_PHASE = 1;
	private static final int END_PHASE = 2;
	
	WordleServer wordleServer;
	User user;
	static DatabaseConnector databaseConnector;// Datenbankverbindung aufstellen

	private String ip;
	private int port;

	private String wordle;
	private String[] words;
	private int count;
	private int phase;
	
	private String tempLoginName;

	static {

		databaseConnector = new DatabaseConnector(null, 0, "wordle.db", null, null);
		
		if (databaseConnector.getErrorMessage() != null) {
			System.err.println(databaseConnector.getErrorMessage());
		}
		
	}

	public Game(WordleServer wordleServer, String pClientIP, int pClientPort) {

		this.wordleServer = wordleServer;
		this.ip = pClientIP;
		this.port = pClientPort;

		send("+OK Hello there");
	}

	public void processMessage(String msg) {

		msg = msg.toLowerCase().trim();

		if (msg.equals("quit")) {
			send("+OK bye");
			wordleServer.closeConnection(ip, port);
			System.exit(0); // TODO remove: Einfacher zum testen
		}

		switch (phase) {
		case LOGIN_PHASE:
			loginPhase(msg);
			break;
		case GAME_PHASE:
			gamePhase(msg);
			break;
		case END_PHASE:
			endPhase(msg);
			break;
		}
	}

	private void loginPhase(String msg) {

		if (msg.startsWith("user ")) {

			if (msg.length() <= 5) {
				sendUniversalError();
				return;
			}
			String args = msg.substring(5);
			
			databaseConnector.executeStatement("SELECT * FROM User WHERE name = '" + args + "'");
			QueryResult result = databaseConnector.getCurrentQueryResult();
			if (result != null && result.getData().length > 0) {
				tempLoginName = result.getData()[0][0];
				send("+OK");
			} else {
				send("-ERR User not found.");
			}

		} else if (msg.startsWith("pass ")) {
			
			if (msg.length() <= 5) {
				sendUniversalError();
				return;
			}
			String args = msg.substring(5);
			
			int pw = args.hashCode();
			databaseConnector.executeStatement("SELECT * FROM User WHERE password = '" + pw + "' AND name = '" + tempLoginName + "'");
			QueryResult result = databaseConnector.getCurrentQueryResult();
			if (result != null && result.getData().length > 0) {
				user = new User(tempLoginName);
				send("+OK welcome");
			} else {
				send("-ERR login not valid");
			}
		} else if (msg.startsWith("wotd")) {
			
			databaseConnector.executeStatement("SELECT word FROM words WHERE id = " + getWOTDIndex());
			QueryResult result = databaseConnector.getCurrentQueryResult();
			if (result != null && result.getData().length > 0) {
				wordle = result.getData()[0][0];
				phase = GAME_PHASE;
				send("+OK game ready");
			} else {
				send("-ERR Fatal error: WOTD could not be generated.");
			}
			
		} else if (msg.startsWith("play")) {
			
			if (user == null) {
				send("-ERR not logged in.");
			} else {
				
			}
		} else {
			sendUniversalError();
		}
	}

	private void gamePhase(String msg) {
		if (msg.startsWith("send")) {

			String args = msg.substring(5);
            //vergleichen von wotd mit
            //ja = spiel beendet und ausgabe word 11111
            //nein = ausgabe 01102 oder so und pr�fen ob man noch ein wort eingebn kann
            // ja game continues nein = game lost
			
		} else if (msg.startsWith("info")) {

		} else if (msg.startsWith("exit")) {

		}
	}

	private void endPhase(String msg) {
		if (msg.startsWith("stat")) {

		} else if (msg.startsWith("play")) {

		}
	}

	private void send(String msg) {
		wordleServer.send(ip, port, msg);
	}
	
	private void sendUniversalError() {
		send("-ERR command not valid in this state");
	}
	
	private int getWOTDIndex() {
		long days = ChronoUnit.DAYS.between(LocalDate.ofEpochDay(0), LocalDate.now());
		int hash = ("" + days).hashCode();
		return hash % 949 + 1;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
}
