package auction.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import javafx.application.Platform;

/**
 * The client's only connection to the server: it owns the socket and its
 * streams. A reading thread waits for lines and hands each one to the listener;
 * send() writes one line. It knows nothing about what the lines mean. The
 * reading thread never calls the listener directly: it hands each line to the
 * FX thread with Platform.runLater, so the listener, and everything it changes,
 * runs only on the FX thread.
 */
public class ServerConnection implements MessageSender {

	private Socket socket_;
	private BufferedReader in_; // used only by the reading thread
	private PrintWriter out_; // used only in send()
	private ConnectionListener listener_;

	/**
	 * Connects to the server. This blocks until connected, so don't call it on
	 * the FX thread.
	 */
	public ServerConnection ( String host, int port, ConnectionListener listener )
	    throws IOException {
		socket_ = new Socket(host,port);
		in_ = new BufferedReader(new InputStreamReader(socket_.getInputStream(),
		                                               StandardCharsets.UTF_8));
		out_ = new PrintWriter(new OutputStreamWriter(socket_.getOutputStream(),
		                                              StandardCharsets.UTF_8));
		listener_ = listener;
	}

	/**
	 * Starts the reading thread.
	 */
	public void start () {
		Thread reader = new Thread(() -> readLoop(),"server-reader");
		reader.setDaemon(true);
		reader.start();
	}

	private void readLoop () {
		try {
			for ( ; true ; ) {
				String line = in_.readLine();
				if ( line == null ) {
					break; // the server closed the connection
				}
				Platform.runLater(() -> listener_.messageReceived(line));
			}
		} catch ( IOException e ) {
			// the connection was lost, or close() was called
		}
		Platform.runLater(() -> listener_.connectionLost());
	}

	/**
	 * Sends one line to the server. May be called from any thread.
	 */
	@Override
	public synchronized void send ( String message ) {
		out_.println(message);
		out_.flush();
	}

	/**
	 * Closes the connection. The reading thread then ends, and the listener is
	 * told connectionLost().
	 */
	public void close () {
		try {
			socket_.close();
		} catch ( IOException e ) {}
	}

}
