package com.tivoli.jmx.tutorial.managedserver;

import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.SortedSet;

public class Listener extends Thread implements ListenerMBean {
  private int port = 10240;
  private boolean listening = true;
  private java.util.SortedSet queue;
  private long requests = 0;

  public Listener(SortedSet queue) {
    this.queue = queue;
  }

  public Listener(SortedSet queue, int port) {
    this.queue = queue;
    this.port = port;
  }

  public int getPort() {
    return port;
  }

  public long getRequests() {
    return requests;
  }

  public synchronized boolean isListening() {
    return listening;
  }

  public void run() {
    try {
      ServerSocket ss = new ServerSocket(this.port);

      while (listening) {
        Socket s = ss.accept();
        Request r = new Request(System.currentTimeMillis(), s);
        synchronized (queue) {
          queue.add(r);
          queue.notify();
        }
        requests++;
      }
    } catch (IOException x) {
      System.out.println(x);
    }
  }

  public void setPort(int port) {
    if (listening) throw new IllegalStateException("Can't set port while listening");
    this.port = port;
  }

  public void startListening() {
    listening = true;
    this.start();
  }

  public void stopListening() {
    listening = false;
  }
}