aboutsummaryrefslogtreecommitdiff
path: root/juick-commands/src/main/java/com/juick/command/Processor.java
blob: 51ce28300ee9f702a9173dcc0a0c4a65abf7a191 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.juick.command;

import com.juick.User;
import com.juick.server.protocol.ProtocolListener;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;

/**
 * @author ma1uta
 */
@Component
@Getter
public class Processor {

    private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class);

    private final Set<Command> commands;
    @Setter
    private ProtocolListener protocolListener;
    private String help;

    @Autowired
    public Processor(Set<Command> commands) {
        this.commands = commands;
    }

    @PostConstruct
    public void init() {
        this.help =
            "HELP - returns this help message.\n" + getCommands().stream().map(Command::help).sorted().collect(Collectors.joining("\n"));
    }

    public String execute(User sender, String command) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Execute command: {}", command);
        }
        command = command != null ? command.trim() : "";
        if ("help".equalsIgnoreCase(command)) {
            LOGGER.debug("Show help");
            return getHelp();
        }
        Command defaultCommand = null;
        for (Command commandItem : getCommands()) {
            Pattern pattern = commandItem.pattern();
            if (pattern != null && pattern.matcher(command).matches()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Found command processor: {}", commandItem.getClass().getName());
                }
                return commandItem.execute(sender, getProtocolListener(), command);
            } else {
                defaultCommand = commandItem;
            }
        }

        if (defaultCommand != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Found default command processor: {}", defaultCommand.getClass().getName());
            }
            return defaultCommand.execute(sender, getProtocolListener(), command);
        }
        LOGGER.debug("Command processor not found, return help");
        return getHelp();
    }
}