package auction.server;

import java.util.ArrayList;
import java.util.List;

/**
 * One auction: the model. It enforces the rules and tells its listeners about
 * changes. No sockets, no message formats: it can be tested without a network.
 * Every handler thread (and the closer thread) uses the same Auction, so every
 * method is synchronized.
 */
public class Auction {

	private String item_;
	private int startPrice_;
	private String highBidder_; // null if no bids yet
	private int highBid_;
	private boolean open_;
	private long lastChange_; // when the auction opened or last got a bid (ms)
	private List<AuctionListener> listeners_;

	public Auction ( String item, int startPrice, long now ) {
		item_ = item;
		startPrice_ = startPrice;
		highBidder_ = null;
		highBid_ = 0;
		open_ = true;
		lastChange_ = now;
		listeners_ = new ArrayList<AuctionListener>();
	}

	public synchronized void addListener ( AuctionListener listener ) {
		listeners_.add(listener);
	}

	public synchronized void removeListener ( AuctionListener listener ) {
		listeners_.remove(listener);
	}

	/**
	 * bidder bids amount.
	 *
	 * @return null if the bid was accepted, otherwise the reason it wasn't
	 */
	public synchronized String bid ( String bidder, int amount, long now ) {
		if ( !open_ ) {
			return "the auction is closed";
		}
		if ( bidder.equals(highBidder_) ) {
			return "you already have the high bid";
		}
		if ( highBidder_ == null && amount < startPrice_ ) {
			return "the opening bid must be at least " + startPrice_;
		}
		if ( highBidder_ != null && amount <= highBid_ ) {
			return "bid more than " + highBid_;
		}

		highBidder_ = bidder;
		highBid_ = amount;
		lastChange_ = now;
		for ( AuctionListener listener : listeners_ ) {
			listener.newHighBid(bidder,amount);
		}
		return null;
	}

	/**
	 * Closes the auction if nothing has happened for quietMillis.
	 */
	public synchronized void closeIfQuiet ( long now, long quietMillis ) {
		if ( open_ && now - lastChange_ >= quietMillis ) {
			open_ = false;
			for ( AuctionListener listener : listeners_ ) {
				if ( highBidder_ == null ) {
					listener.unsold();
				} else {
					listener.sold(highBidder_,highBid_);
				}
			}
		}
	}

	public synchronized boolean isOpen () {
		return open_;
	}

	public synchronized String getItem () {
		return item_;
	}

	public synchronized int getStartPrice () {
		return startPrice_;
	}

	/** @return the high bidder, or null if there are no bids */
	public synchronized String getHighBidder () {
		return highBidder_;
	}

	public synchronized int getHighBid () {
		return highBid_;
	}

}
