package pircbot.adapter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.jibble.pircbot.PircBot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import chatbot.client.ConnectionListener;
import chatbot.client.Message;
import chatbot.client.MessageChannel;
import chatbot.client.MessageListener;
public class PircChatEngine extends PircBot implements MessageChannel {
private static final Logger logger = LoggerFactory.getLogger(PircChatEngine.class);
private static final String NEWLINE_REGEX = "\\r?\\n";
private final String server;
private final int port;
private final List<ConnectionListener> connectionListeners;
private final List<MessageListener> messageListeners;
private String channel;
public PircChatEngine(String server, int port, String username) {
this.server = server;
this.port = port;
this.setName(username);
this.connectionListeners = new ArrayList<ConnectionListener>();
this.messageListeners = new ArrayList<MessageListener>();
}
public MessageChannel connectChannel(String channel, String password) {
this.joinChannel(channel, password);
this.channel = channel;
return this;
}
public void connect() throws NickAlreadyInUseException, IOException, IrcException {
this.connect(server, port, null);
}
@Override
protected void onConnect() {
logger.info("Pircbot engine connected to server [{}] on port [{}]", server, port);
for (ConnectionListener listener : this.connectionListeners) {
listener.onConnectionSuccessful();
}
}
@Override
public void registerListener(MessageListener listener) {
this.messageListeners.add(listener);
}
@Override
public void sendMessage(String message) {
logger.info("Sending message to channel: " + channel);
String[] split = message.split(NEWLINE_REGEX);
Arrays.asList(split);
for (String line : split) {
this.sendMessage(channel, line);
}
}
public void addChatEngineListener(ConnectionListener listener) {
this.connectionListeners.add(listener);
}
@Override
protected void onMessage(String channel, String sender, String login, String hostname, String payload) {
logger.info("Recieved message [" + payload + "]");
for (MessageListener listener : this.messageListeners) {
Message message = new Message(sender, payload);
listener.onMessageReceived(message);
}
}
}