package vs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * iterative server for var.sockets.tcp.echo Echo service. waits for the next
 * client to connect, sends greeting message to client, reads line by line from
 * client and sends it back adding "echo: " in front of each line until
 * connection is closed by client.
 *
 * @author Sandro Leuchter
 *
 */
public class EchoServerIterativ {
	/**
	 * port on which this service is currently listening on localhost
	 */
	private final int port;
	/**
	 * current maximum length of the queue of incoming connections.
	 */
	private final int backlog;

	/**
	 * the only constructor for this class
	 *
	 * @param port    port on which this service will be listening on localhost
	 * @param backlog requested maximum length of the queue of incoming connections.
	 */
	public EchoServerIterativ(int port, int backlog) {
		this.port = port;
		this.backlog = backlog;
	}

	/**
	 * creates server socket on localhost:port, infinitely handles connections to
	 * clients one after another
	 */
	public void start() {
		try (ServerSocket serverSocket = new ServerSocket(this.port, this.backlog)) {
			System.out.println("EchoServer (iterativ) auf " + serverSocket.getLocalSocketAddress() + " gestartet ...");
			while (true) {
				handleClient(serverSocket);
			}
		} catch (IOException e) {
			System.err.println(e);
		}
	}

	/**
	 * waits for the next client to connect to server, sends greeting message to
	 * client, reads line by line from client and sends it back adding "echo: " in
	 * front of each line until connection is closed by client.
	 *
	 * @param server "welcome socket" on which server is listening for clients
	 */
	private void handleClient(ServerSocket server) {
		SocketAddress socketAddress = null;
		try (Socket socket = server.accept();
				BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
			socketAddress = socket.getRemoteSocketAddress();
			System.out.println("Verbindung zu " + socketAddress + " aufgebaut");
			out.println("Server ist bereit ...");
			String input;
			while ((input = in.readLine()) != null) {
				System.out.println(socketAddress + ">> [" + input + "]");
				out.println("echo: " + input);
			}
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			System.out.println("Verbindung zu " + socketAddress + " abgebaut");
		}
	}

	/**
	 * main method: entrypoint to run service
	 *
	 * @param args args[0] must be the port number of the server (int); rest of args
	 *             is ignored
	 */
	public static void main(String[] args) {
		int port = Integer.parseInt(args[0]);
		int backlog = 50;
		if (args.length == 2) {
			backlog = Integer.parseInt(args[1]);
		}

		new EchoServerIterativ(port, backlog).start();
	}
}
