package connection.server;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import main.settings.Settings;
import common.connection.client.AbstractClientSideConnector;
import common.connection.client.ConnectionAttempt;
import common.connection.client.ConnectionAttempterInterface;
import ui.misc.MessageBox;
public class ConnectionManager implements ConnectionManagerInterface,
ConnectionAttempterInterface
{
private volatile ServerConnection connection;
private volatile boolean connected;
private ArrayList<ConnectionStateListener> listeners;
public ConnectionManager()
{
connected = false;
listeners = new ArrayList<ConnectionStateListener>();
}
public synchronized void addListener(ConnectionStateListener listener)
{
listeners.add(listener);
}
public synchronized void connect(String host, int port)
{
disconnect();
for (ConnectionStateListener listener : listeners)
{
listener.onConnecting();
}
new ConnectionAttempt(this, new InetSocketAddress(host, port),
Settings.connection.security.to_server);
}
public synchronized void disconnect()
{
if (!connected)
{
return;
}
connected = false;
connection.terminate();
connection = null;
}
public boolean isConnected()
{
return connected;
}
public ServerConnection getConnection()
{
if (!connected)
{
throw new IllegalStateException();
}
return connection;
}
public AbstractClientSideConnector getConnector()
{
return new ServerConnector(this);
}
public void notifyConnected(ServerConnection connection)
{
this.connection = connection;
connected = true;
for (ConnectionStateListener listener : listeners)
{
listener.onConnected(connection);
listener.updateConnectionState(true);
}
}
public synchronized void notifyFailure()
{
for (ConnectionStateListener listener : listeners)
{
listener.onFailed();
}
MessageBox.showError("Connection failed.", "Connection Failed");
}
public synchronized void notifyDisconnection()
{
connected = false;
connection = null;
for (ConnectionStateListener listener : listeners)
{
listener.onDisconnected();
listener.updateConnectionState(false);
}
}
}