import java.io.*;
import java.net.*;
import java.util.*;

public class Server {
  ServerSocket ss;
  Vector questions;
  int index;

  public Server() {
    try {
      Socket s;
      boolean done=false;
      questions = new Vector();
      questions.add(new Results());
      index = 0;
      ss = new ServerSocket(8888);
      while (!done) {
	s = ss.accept();
	done = process(s);
      }
      ss.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private boolean process(Socket s) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String cmd = br.readLine();
    boolean done = false;
    if ("vote".equals(cmd)) {
      Results rs = (Results)questions.get(index);
      rs.addVote(br.readLine(),s.getInetAddress());
    } else if ("results".equals(cmd)) {
      Results rs = (Results)questions.get(index);
      rs.output(new PrintWriter(s.getOutputStream()));
    } else if ("new".equals(cmd)) {
      questions.add(new Results());
      index++;
    } else if ("prev".equals(cmd)) {
      if (index > 0) index--;
    } else if ("next".equals(cmd)) {
      if (index < questions.size()-1) index++;
    } else if ("shutdown".equals(cmd)) {
      done = true;
    }
    s.close();
    return done;
  }

  public static void main(String args[]) {
    new Server();
  }
}
