package auction.server;

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;

/**
 * Talks to one bidder: turns the bidder's messages into calls on the auction,
 * and the auction's notifications into messages. All of the protocol's syntax
 * lives here; the auction knows nothing about it. It keeps this connection's
 * conversation state: connected (not yet a bidder), bidding, or ended (the
 * auction closed). The state decides which messages are allowed. run() is
 * executed by this bidder's thread. The listener methods are called by
 * whichever thread changed the auction, so send() is synchronized.
 */
public class BidderHandler implements Runnable, AuctionListener {

	/** The conversation states of one connection. */
	private enum Phase {
		CONNECTED, BIDDING, ENDED
	}

	private Socket socket_;
	private Auction auction_;
	private BufferedReader in_; // used only by this bidder's thread
	private PrintWriter out_; // used only in send()
	private String name_; // null until JOIN; used only by this bidder's thread

	// changed by this bidder's thread (CONNECTED to BIDDING) and by the closer
	// thread (to ENDED, in sold() and unsold()), so volatile: each thread
	// must see the other's change
	private volatile Phase phase_;

	public BidderHandler ( Socket socket, Auction auction ) throws IOException {
		socket_ = socket;
		auction_ = auction;
		in_ = new BufferedReader(new InputStreamReader(socket.getInputStream(),
		                                               StandardCharsets.UTF_8));
		out_ = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),
		                                              StandardCharsets.UTF_8));
		name_ = null;
		phase_ = Phase.CONNECTED;
	}

	@Override
	public void run () {
		try {
			send("HELLO auction/1");
			for ( ; true ; ) {
				String line = in_.readLine();
				if ( line == null || phase_ == Phase.ENDED ) {
					break; // the bidder left, or the auction is over
				}
				String[] words = line.trim().split(" ");
				if ( words[0].equals("QUIT") ) {
					break;
				} else if ( words[0].equals("JOIN") ) {
					handleJoin(words);
				} else if ( words[0].equals("BID") ) {
					handleBid(words);
				} else {
					send("ERROR unknown message: " + words[0]);
				}
			}
		} catch ( IOException e ) {
			// the connection was closed
		} finally {
			auction_.removeListener(this);
			close();
		}
	}

	private void handleJoin ( String[] words ) {
		if ( phase_ == Phase.BIDDING ) {
			send("ERROR already joined");
		} else if ( words.length != 2 ) {
			send("ERROR usage: JOIN name (one word)");
		} else {
			// hold the auction's lock while reporting its state and starting to
			// listen, so no bid can slip in between and be missed
			synchronized ( auction_ ) {
				if ( !auction_.isOpen() ) {
					send("ERROR the auction is closed");
					return;
				}
				name_ = words[1];
				phase_ = Phase.BIDDING;
				send("WELCOME " + name_);
				send("ITEM " + auction_.getStartPrice() + " " + auction_.getItem());
				if ( auction_.getHighBidder() != null ) {
					send("HIGH " + auction_.getHighBid() + " "
					    + auction_.getHighBidder());
				}
				auction_.addListener(this);
			}
		}
	}

	private void handleBid ( String[] words ) {
		if ( phase_ != Phase.BIDDING ) {
			send("ERROR JOIN first");
			return;
		}
		if ( words.length != 2 ) {
			send("ERROR usage: BID amount");
			return;
		}
		int amount;
		try {
			amount = Integer.parseInt(words[1]);
		} catch ( NumberFormatException e ) {
			send("ERROR usage: BID amount (whole dollars)");
			return;
		}
		String problem = auction_.bid(name_,amount,System.currentTimeMillis());
		if ( problem != null ) {
			send("ERROR " + problem);
		}
		// if accepted, newHighBid() tells everyone, including this bidder
	}

	@Override
	public void newHighBid ( String bidder, int amount ) {
		send("HIGH " + amount + " " + bidder);
	}

	@Override
	public void sold ( String bidder, int amount ) {
		phase_ = Phase.ENDED;
		send("SOLD " + amount + " " + bidder);
		close();
	}

	@Override
	public void unsold () {
		phase_ = Phase.ENDED;
		send("UNSOLD");
		close();
	}

	/**
	 * Sends one line to this bidder. Called from any thread.
	 */
	private synchronized void send ( String message ) {
		out_.println(message);
		out_.flush();
	}

	private void close () {
		try {
			socket_.close(); // also wakes this bidder's thread if it's blocked
			                 // reading
		} catch ( IOException e ) {}
	}

}
