Move event sending into the command handler.
[xudocci.git] / src / main / java / net / pterodactylus / irc / connection / SimpleCommandHandler.java
1 package net.pterodactylus.irc.connection;
2
3 import java.util.HashMap;
4 import java.util.List;
5 import java.util.Map;
6
7 import net.pterodactylus.irc.Reply;
8 import net.pterodactylus.irc.Source;
9
10 import com.google.common.base.Optional;
11 import com.google.common.eventbus.EventBus;
12
13 /**
14  * Handler that can send events associated with commands to an {@link
15  * EventBus}.
16  *
17  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
18  */
19 public class SimpleCommandHandler implements Handler {
20
21         private final Map<String, EventProcessor> commandEventSenders =
22                         new HashMap<>();
23         private final EventBus eventBus;
24
25         public SimpleCommandHandler(EventBus eventBus) {
26                 this.eventBus = eventBus;
27         }
28
29         public SimpleCommandHandler addCommand(String command,
30                         EventProcessor eventProcessor) {
31                 commandEventSenders.put(command.toLowerCase(), eventProcessor);
32                 return this;
33         }
34
35         @Override
36         public boolean willHandle(Reply reply) {
37                 return commandEventSenders.containsKey(reply.command().toLowerCase());
38         }
39
40         @Override
41         public void handleReply(Reply reply) {
42                 EventProcessor eventProcessor =
43                                 commandEventSenders.get(reply.command().toLowerCase());
44                 eventBus.post(eventProcessor.createEvent(reply.source(),
45                                 reply.parameters()));
46         }
47
48         /**
49          * Interface for event creators.
50          *
51          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52          */
53         @FunctionalInterface
54         public static interface EventProcessor {
55
56                 Object createEvent(Optional<Source> source, List<String> parameters);
57
58         }
59
60 }