/* File: PollServer.java
 * ---------------------
 * This file is the server program for a Trivia game.  It listens
 * for votes coming in over the network via Requests, and counts
 * up the votes it receives.  It allows the user of this program
 * to reset the votes (by posting a new question) and display
 * the votes.
 */

import acm.program.*;
import javax.swing.*;
import java.awt.event.*;

public class PollServer extends ConsoleProgram implements SimpleServerListener {
	
	// 1. make a Server object
	// notifies us when we receive a request
	private SimpleServer server = new SimpleServer(this, 8080);
	
	// The text field where the user enters questions
	private JTextField textField;
	
	// The length-4 array counting the votes for A/B/C/D
	int[] votes = new int[4];
	
	public void init() {	
		setFont("Courier-24");
		
		// 2. start the server
		// start listening for requests
		server.start();
		
		// Add interactors
		add(new JButton("Display Votes"), NORTH);
		textField = new JTextField(20);
		add(textField, SOUTH);
		add(new JButton("Post Question"), SOUTH);
		addActionListeners();
	}
	
	public void actionPerformed(ActionEvent e) {
		String actionCmd = e.getActionCommand();
		if (actionCmd.equals("Display Votes")) {
			// Display the votes for A/B/C/D
			for (int i = 0; i < votes.length; i++) {
				char currentAnswer = (char)('A' + i);
				println("(" + currentAnswer + "): " + votes[i] + " votes");
			}
		} else if (actionCmd.equals("Post Question")) {
			// Clear the screen and the vote counts for the new question
			clearConsole();
			votes = new int[4];
			println(textField.getText());
			println("Waiting for responses....");
			textField.setText("");
		}
	}
	
	// 3. Implement requestMade
	// This method is called whenever a request is received.
	public String requestMade(Request request) {
		String cmd = request.getCommand();
		if (cmd.equals("vote")) {
			// Add one to our array of vote counts for their vote
			String vote = request.getParam("answer");
			votes[vote.charAt(0) - 'A']++;
			return "Vote \"" + vote + "\" received!";
		} else {
			return "Unknown command.";
		}
	}
}
