package auction.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * An auction server: one item, any number of bidders, each on its own thread.
 * The auction closes when nobody has bid for a while. Protocol auction/1 (one
 * message per line, words separated by spaces):
 *
 * <pre>
 * client -> server
 *   JOIN name               name: one word
 *   BID amount              whole dollars
 *   QUIT
 *
 * server -> client
 *   HELLO auction/1         on connect: the server speaks first
 *   WELCOME name            joined
 *   ITEM start description  the item and its starting price (after WELCOME)
 *   HIGH amount name        the current high bid (after ITEM, if any; and
 *                           to everyone after each accepted bid)
 *   ERROR reason            the message was rejected; nothing changed
 *   SOLD amount name        the auction closed with a winner; then the
 *                           server closes the connection
 *   UNSOLD                  the auction closed with no bids; then the
 *                           server closes the connection
 * </pre>
 *
 * Optional argument: seconds without a bid before the auction closes (default
 * 20).
 */
public class AuctionServer {

	public static final int PORT = 5003;

	public static void main ( String[] args ) throws IOException {
		long quietMillis = 20000;
		if ( args.length > 0 ) {
			quietMillis = Long.parseLong(args[0]) * 1000;
		}

		Auction auction = new Auction("vintage typewriter, works, some rust",20,
		                              System.currentTimeMillis());

		Thread closer = new Thread(new Closer(auction,quietMillis),"closer");
		closer.setDaemon(true);
		closer.start();

		ServerSocket server = new ServerSocket(PORT);
		System.out.println("auction server listening on port " + PORT);
		int count = 0;
		for ( ; true ; ) {
			Socket socket = server.accept();
			count++;
			try {
				new Thread(new BidderHandler(socket,auction),"bidder-" + count).start();
			} catch ( IOException e ) {
				socket.close();
			}
		}
	}

	/**
	 * Checks twice a second whether the auction should close.
	 */
	private static class Closer implements Runnable {

		private Auction auction_;
		private long quietMillis_;

		public Closer ( Auction auction, long quietMillis ) {
			auction_ = auction;
			quietMillis_ = quietMillis;
		}

		@Override
		public void run () {
			for ( ; auction_.isOpen() ; ) {
				try {
					Thread.sleep(500);
				} catch ( InterruptedException e ) {}
				auction_.closeIfQuiet(System.currentTimeMillis(),quietMillis_);
			}
		}

	}

}
