package ua.vydai.chat.server.controller;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import ua.vydai.chat.server.model.ChatServerModel;
import ua.vydai.chat.server.model.interfaces.*;
import ua.vydai.chat.server.view.SimpleAwtServerView;
import ua.vydai.chat.server.view.interfaces.*;
public class ServerController implements ActionListener {
public static void main(String[] args) {
ServerController controller = new ServerController(new ChatServerModel());
controller.createView(SimpleAwtServerView.getFactory());
// controller.createView(SimpleAwtServerView.getFactory()); // FOR DEBUG
}
public ServerController(ServerModel model) {
this.model = model;
}
public void actionPerformed(ActionEvent event) {
ServerView view = (ServerView) event.getSource();
if (event.getActionCommand().equals(ServerView.ACTION_CLOSE)) {
view.close();
views.remove(view);
if (views.size() == 0) {
model.stopServer();
System.exit(0);
}
} else if (event.getActionCommand().equals(ServerView.ACTION_START)) {
int port;
try {
port = Integer.parseInt(view.getPort());
} catch (NumberFormatException e) {
view.showError("Port should contain only digits");
return;
}
if (port < 1024 || port > 65536) {
view.showError("Port must be between 1024 and 65536");
return;
}
if (!model.isPortAvailable(port)) {
view.showError("Port is not available. Try to take another port");
return;
}
model.startServer(port);
} else if (event.getActionCommand().equals(ServerView.ACTION_STOP)) {
model.stopServer();
}
}
private void createView(ServerViewFactory factory) {
ServerView view = factory.createView(model);
views.add(view);
view.addActionListener(this);
view.show();
}
private List<ServerView> views = new ArrayList<ServerView>();
private ServerModel model;
}