package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import server.match.Match;

public class NetworkUser {
	private String name;
	private Socket client;
	private DataOutputStream dout;
	private DataInputStream din;
	private Thread receivethread;
	private Match match;
	private int pid;

	// A thread which handles the server communication to a client
	public NetworkUser(Socket client) {
		this.client = client;
		try {
			dout = new DataOutputStream(client.getOutputStream());
			din = new DataInputStream(client.getInputStream());
		} catch (IOException e) {
			match.stopMatch();
		}
		try {
			client.setSoTimeout(5000);
			name = din.readUTF();
			System.out.println(name);
			client.setSoTimeout(0);
		} catch (IOException e) {
		}
		receivethread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					receiveMessage();
				}
			}
		});
	}

	/* NETWORK CONTROL METHODS */

	public boolean checkConnection() {
		try {
			dout.writeUTF("0");
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	public void startMatch(String p1, String p2, int pid, Match match) {
		sendMessage("1|" + p1 + "|" + p2);
		this.pid = pid;
		this.match = match;
		receivethread.start();
	}

	public void sendOverlayText(String text) {
		sendMessage("3|" + text + "  ");
	}

	public void sendUpdateMessage(String m) {
		sendMessage("2|" + m);
	}

	public void sendChatMessage(String m) {
		sendMessage("4|" + m);
	}

	private void sendMessage(String m) {
		try {
			dout.writeUTF(m);
		} catch (IOException e) {
			System.err.println("User disconnected");
			match.stopMatch();
		}
	}

	public void receiveMessage() {
		try {
			String message = din.readUTF();
			String[] messagesplit = message.split("\\|");
			switch (messagesplit[0]) {
			case "1": // Player input information
				match.setPlayerDirection(pid, Integer.parseInt(messagesplit[1]));
				if (Integer.parseInt(messagesplit[2]) == 1) {
					match.playerShoot(pid);
				}
				break;
			case "2":
				match.sendChatMessage("[" + name + "] " + messagesplit[1]);
				break;
			}

		} catch (IOException e) {
			System.err.println("User disconnected");
			match.stopMatch();
		}
	}

	public void close() throws IOException {
		receivethread.stop();
		din.close();
		dout.close();
		client.close();
	}

	/* GETTERS AND SETTERS */

	/**
	 * @return the name of the user
	 */
	public String getName() {
		return name;
	}
}
