// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package gamesim;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    private int expected;
    private ServerSocket ss;
    private List<Client> cli = new ArrayList<Client>();
    private int curr = -1;
    public Server(int expected) {
        this.expected = expected;
    }
    private void next() {
        curr = (curr + 1) % cli.size();
        cli.get(curr).send(Protocol.YOUR_TURN);
    }
    private void sendAllClients(String msg) {
        for(Client c : cli) {
            c.send(msg);
        }
    }
    public void runGame() {
        try {
            ss = new ServerSocket(Protocol.PORT);
            while(cli.size() < expected) {
                Socket s = ss.accept();
                cli.add(new Client(s, cli.size()));
                System.out.printf("Client #%d connected\n", cli.size());
            }
            System.out.println("Game started");
            next();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    private void shutdownGame() {
        sendAllClients(Protocol.EXIT);
        for(Client c : cli) {
            c.close();
        }
        try {
            ss.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Server srv = new Server(2);
        srv.runGame();
    }
    public class Client {
        private int id;
        private Socket s;
        private PrintWriter pw;
        private BufferedReader br;
        private boolean closing = false;
        public Client(Socket s, int id) {
            try {
                this.s = s;
                this.id = id;
                pw = new PrintWriter(s.getOutputStream());
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                (new ReadFromClient()).start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        @Override
        public int hashCode() {
            return id;
        }
        @Override
        public boolean equals(Object obj) {
            if((obj instanceof Client) && (id == ((Client)obj).id)) {
                return true;
            } else {
                return false;
            }
        }
        private void send(String msg) {
            pw.println(msg);
            pw.flush();
        }
        private void close() {
            try {
                br.close();
                pw.close();
                s.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        public class ReadFromClient extends Thread {
            public void run() {
                try {
                    String line;
                    while((line = br.readLine()) != null) {
                        switch(line) {
                            case Protocol.MOVE : next();
                                                 break;
                            case Protocol.EXIT : closing = true;
                                                 cli.remove(Client.this);
                                                 close();
                                                 shutdownGame();
                                                 return;
                            default: // ignore
                                     break;
                        }
                    }
                } catch (IOException ex) {
                    if(!closing) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
}
