//
// TTTServiceImpl.java: implementation side of Tic Tac Toe game server
//

import java.rmi.*;
import java.rmi.server.*;
import java.util.*;

class TTTServiceImpl extends UnicastRemoteObject
   implements TTTService
{
   //--------------------------------------------------
   // TODO: consider modifying the following to be unique
   public final static String ServiceName = "ttt-service";

   // TODO: change following port to a value between 10000 and 30000
   // The conventional RMI port is 1099, but this will not work on most hosts
   public final static int ServicePort = 10000;

   // TODO: update following to hostname of server
   //public final static String ServiceHost = "server.host.name";
   public final static String ServiceHost = "esubmit.msoe.edu";
   //--------------------------------------------------

   // the object being served up
   protected TTTBoard board = new TTTBoard();

   // Required constructor for RMI; body can be empty
   public TTTServiceImpl() throws RemoteException { super(); }

   // implementations of methods in CounterService
   public TTTBoard getState() throws RemoteException
   {
      return board;
   }

   public void pick(int col, int row) throws RemoteException
   {
      board.pick(col, row);
      updateClients();
   }

   public void reset() throws RemoteException
   {
      board.reset();
      updateClients();
   }

   // the next 5 lines allow the server to track who the clients are
   //   the list is synchronized to avoid concurrency problems
   //   (this model works assuming all clients start up at the same time)
   List<TTTClientRemote> clients = Collections.synchronizedList(new LinkedList<>());
   public void register(TTTClientRemote newClient) throws RemoteException
   {
      clients.add(newClient);
   }

   public void updateClients()
   {
      Iterator it = clients.iterator();
      while ( it.hasNext() )
      {
         TTTClientRemote client = (TTTClientRemote)it.next();
         try
         {
            client.updateBoard(board);
         }
         catch ( Exception e )
         {
            // note system does not halt in such situations!
            System.out.println("Could not update client " + client.toString());
         }
      }
          
   }

   public static void main(String args[])
   {
      System.out.println("Initializing TTTService...");
      try
      {
         TTTService cserv = new TTTServiceImpl();
         String serverObjectName = "rmi://localhost:" + ServicePort
            + "/" + ServiceName;
         Naming.rebind(serverObjectName, cserv);        // register service with RMI
         System.out.println("TTTService running.");
      }
      catch (Exception e)
      {
         System.out.println("Exception: " + e.getMessage());
         e.printStackTrace();
      }
   }
}
