Split command reader into separate commands.
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / ui / stdin / DisconnectCommand.java
1 /*
2  * XdccDownloader - DisconnectCommand.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.xdcc.ui.stdin;
19
20 import static java.util.Arrays.asList;
21
22 import java.io.IOException;
23 import java.io.Writer;
24 import java.util.Collection;
25 import java.util.List;
26
27 import net.pterodactylus.irc.Connection;
28 import net.pterodactylus.xdcc.core.Core;
29
30 import com.google.common.primitives.Ints;
31
32 /**
33  * Command that will disconnect a {@link Connection}.
34  *
35  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
36  * @see State#getLastConnections()
37  */
38 public class DisconnectCommand implements Command {
39
40         /** The core to operate on. */
41         private final Core core;
42
43         /**
44          * Creates a new disconnect command.
45          *
46          * @param core
47          *              The core to operate on
48          */
49         public DisconnectCommand(Core core) {
50                 this.core = core;
51         }
52
53         //
54         // COMMAND METHODS
55         //
56
57         @Override
58         public String getName() {
59                 return "disconnect";
60         }
61
62         @Override
63         public Collection<String> getAliases() {
64                 return asList("close");
65         }
66
67         @Override
68         public State execute(State state, List<String> parameters, Writer outputWriter) throws IOException {
69                 if ((parameters.isEmpty() || ("all".equals(parameters.get(0))))) {
70                         for (Connection connection : state.getLastConnections()) {
71                                 core.closeConnection(connection);
72                         }
73                 } else {
74                         Integer index = Ints.tryParse(parameters.get(0));
75                         if ((index != null) && (index < state.getLastConnections().size())) {
76                                 core.closeConnection(state.getLastConnections().get(index));
77                         }
78                 }
79                 return state;
80         }
81
82 }