/*
 * This file is part of the Vamsas Client version 0.2. 
 * Copyright 2010 by Jim Procter, Iain Milne, Pierre Marguerite, 
 *  Andrew Waterhouse and Dominik Lindner.
 * 
 * Earlier versions have also been incorporated into Jalview version 2.4 
 * since 2008, and TOPALi version 2 since 2007.
 * 
 * The Vamsas Client is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *  
 * The Vamsas Client is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with the Vamsas Client.  If not, see <http://www.gnu.org/licenses/>.
 */
package uk.ac.vamsas.client.picking;

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

import org.apache.commons.logging.Log;

/**
 * Server class that listens for incoming connections on a predefined port.
 */
class PickServer extends Thread {
  private Log logger = org.apache.commons.logging.LogFactory
      .getLog(uk.ac.vamsas.client.picking.PickServer.class);

  // The port number we'll listen on
  static final int PORT = 53782;

  private ServerSocket serverSocket;

  // Set to true once the server is established
  private boolean isServer = false;

  // Set to false when server is shutting down
  private boolean isAlive = true;

  private SocketManager manager;

  /**
   * Constructs a new instance of the server (but doesn't start it).
   * 
   * @param manager
   *          a reference to the pick manager that owns this server
   */
  PickServer(SocketManager manager) {
    this.manager = manager;
  }

  /**
   * Returns true if this server instance is running. Return true if this server
   * instance is running
   */
  boolean isServer() {
    return isServer;
  }

  /**
   * Attempts to create the server by opening a server socket on the port.
   * 
   * @return true if the server was created; false otherwise
   */
  boolean createServer() {
    try {
      serverSocket = new ServerSocket(PORT);
      start();

      return isServer = true;
    } catch (IOException e) {
      logger.debug("SERVER: " + e);
      return false;
    }
  }

  /**
   * Thread listening method - loops indefinitely listening for connections.
   * When one is received, the socket object is passed to the manager so it can
   * make a full client connection for further comms.
   */
  public void run() {
    logger.debug("SERVER: listening on " + PORT + " - SERVER");

    // Loop forever, accepting connectons from other clients
    // TODO: add in the ability to terminate the server if a VAMSAS session
    // is ended
    while (isAlive) {
      try {
        Socket socket = serverSocket.accept();
        logger.info("SERVER: connection detected");
        if (isAlive)
          manager.addEndPoint(socket);
      } catch (IOException e) {
      }
    }
  }

  void terminate() {
    logger.debug("Server shutting down...");
    isAlive = false;
    try {
      serverSocket.close();
    } catch (Exception e) {
      logger.error(e);
    }
    logger.debug("Server shut down complete.");
  }
}
