package auction.client;

/**
 * All of auction/1's syntax on the client side: it turns the controller's
 * intentions (join, bid, quit) into messages, and the server's messages into
 * updates to the auction state (the client's copy of the item and the high
 * bid). It is also the only class that changes the conversation state (not
 * joined, joining, bidding, bid pending, ended, disconnected). AuctionState
 * holds that state, so the views can show it, but the protocol updates it as
 * requests go out and messages come in, and checks it before sending, so it
 * never sends a request that isn't allowed yet and never has two requests
 * outstanding. Used only on the FX thread: the controller calls it there, and
 * ServerConnection delivers messages there.
 */
public class AuctionProtocol implements ConnectionListener {

	public static final String VERSION = "auction/1";

	private AuctionState state_;
	private MessageSender server_; // null until connected

	public AuctionProtocol ( AuctionState state ) {
		state_ = state;
		server_ = null;
	}

	public void setServer ( MessageSender server ) {
		server_ = server;
	}

	// ---------- requests: the controller's intentions become messages ----------

	/**
	 * Asks to join as name. Allowed only when not yet joined.
	 */
	public void join ( String name ) {
		if ( state_.getPhase() != AuctionState.Phase.NOT_JOINED ) {
			return;
		}
		state_.setName(name);
		state_.setPhase(AuctionState.Phase.JOINING);
		state_.setMessage("joining…");
		server_.send("JOIN " + name);
	}

	/**
	 * Bids amount whole dollars. Allowed only when joined and no other bid is
	 * waiting for an answer.
	 */
	public void bid ( int amount ) {
		if ( state_.getPhase() != AuctionState.Phase.BIDDING ) {
			return;
		}
		state_.setPhase(AuctionState.Phase.BID_PENDING);
		state_.setMessage("bidding $" + amount + "…");
		server_.send("BID " + amount);
	}

	/**
	 * Leaves the auction. The server then closes the connection.
	 */
	public void quit () {
		AuctionState.Phase phase = state_.getPhase();
		if ( phase == AuctionState.Phase.ENDED
		    || phase == AuctionState.Phase.DISCONNECTED || server_ == null ) {
			return;
		}
		state_.setPhase(AuctionState.Phase.ENDED);
		state_.setMessage("you left the auction");
		server_.send("QUIT");
	}

	// ---------- reports: the server's messages become changes to the state
	// ----------

	@Override
	public void messageReceived ( String line ) {
		String[] parts = line.split(" ",2); // the command word, then the rest
		String command = parts[0];
		String rest = (parts.length > 1 ? parts[1] : "");
		try {
			if ( command.equals("HELLO") ) {
				handleHello(rest);
			} else if ( command.equals("WELCOME") ) {
				handleWelcome();
			} else if ( command.equals("ITEM") ) {
				String[] words = rest.split(" ",2); // start price, then the description
				state_.setItem(Integer.parseInt(words[0]),words[1]);
			} else if ( command.equals("HIGH") ) {
				String[] words = rest.split(" ");
				handleHigh(Integer.parseInt(words[0]),words[1]);
			} else if ( command.equals("ERROR") ) {
				handleError(rest);
			} else if ( command.equals("SOLD") ) {
				String[] words = rest.split(" ");
				handleSold(Integer.parseInt(words[0]),words[1]);
			} else if ( command.equals("UNSOLD") ) {
				state_.setPhase(AuctionState.Phase.ENDED);
				state_.setMessage("the auction closed with no bids");
			} else {
				ignore(line);
			}
		} catch ( NumberFormatException | ArrayIndexOutOfBoundsException e ) {
			ignore(line); // a message we can't make sense of
		}
	}

	private void handleHello ( String version ) {
		if ( state_.getPhase() != AuctionState.Phase.WAITING_FOR_HELLO ) {
			return;
		}
		if ( !version.equals(VERSION) ) {
			state_.setPhase(AuctionState.Phase.DISCONNECTED);
			state_.setMessage("the server speaks " + version + "; this client needs "
			    + VERSION);
			return;
		}
		state_.setPhase(AuctionState.Phase.NOT_JOINED);
		state_.setMessage("connected: enter a name and join");
	}

	private void handleWelcome () {
		if ( state_.getPhase() != AuctionState.Phase.JOINING ) {
			return;
		}
		state_.setPhase(AuctionState.Phase.BIDDING);
		state_.setMessage("joined as " + state_.getName());
	}

	private void handleHigh ( int amount, String bidder ) {
		state_.setHighBid(amount,bidder);
		// HIGH is everyone's update and also this bidder's acknowledgement:
		// if it names us while our bid is pending, our bid was accepted.
		// (This assumes names are unique, which auction/1 doesn't promise.)
		AuctionState.Phase phase = state_.getPhase();
		if ( phase == AuctionState.Phase.BID_PENDING
		    && bidder.equals(state_.getName()) ) {
			state_.setPhase(AuctionState.Phase.BIDDING);
			state_.setMessage("your bid of $" + amount + " is the high bid");
		} else if ( phase == AuctionState.Phase.BIDDING
		    && !bidder.equals(state_.getName()) ) {
			    state_.setMessage(bidder + " bid $" + amount);
		    }
		// while our own bid is pending, keep showing "bidding…": the answer
		// to it is still on its way
	}

	private void handleError ( String reason ) {
		AuctionState.Phase phase = state_.getPhase();
		if ( phase == AuctionState.Phase.JOINING ) {
			if ( reason.equals("the auction is closed") ) {
				// only the reason's text tells this error apart from the others
				state_.setPhase(AuctionState.Phase.ENDED);
				state_.setMessage("the auction has already closed");
			} else {
				state_.setName(null);
				state_.setPhase(AuctionState.Phase.NOT_JOINED);
				state_.setMessage("couldn't join: " + reason);
			}
		} else if ( phase == AuctionState.Phase.BID_PENDING ) {
			state_.setPhase(AuctionState.Phase.BIDDING);
			state_.setMessage("bid refused: " + reason);
		} else {
			state_.setMessage("server: " + reason);
		}
	}

	private void handleSold ( int amount, String bidder ) {
		state_.setHighBid(amount,bidder);
		state_.setPhase(AuctionState.Phase.ENDED);
		if ( bidder.equals(state_.getName()) ) {
			state_.setMessage("you won, at $" + amount);
		} else {
			state_.setMessage("sold to " + bidder + " for $" + amount);
		}
	}

	private void ignore ( String line ) {
		System.err.println("ignoring unexpected message: " + line);
	}

	@Override
	public void connectionLost () {
		if ( state_.getPhase() == AuctionState.Phase.ENDED ) {
			return; // expected: the server closes the connection at the end
		}
		state_.setPhase(AuctionState.Phase.DISCONNECTED);
		state_.setMessage("lost the connection to the server");
	}

}
