aboutsummaryrefslogtreecommitdiff
path: root/juick-commands/src/main/java/com/juick/command/ShowMessage.java
blob: 741f98b93a92e885e1c07ec4e790fce997acc01c (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
package com.juick.command;

import com.juick.Message;
import com.juick.User;
import com.juick.formatters.PlainTextFormatter;
import com.juick.service.MessagesService;
import lombok.Getter;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author ma1uta
 */
@Component
@Getter
public class ShowMessage extends MultiArgsCommand {

    private static final Pattern PATTERN = Pattern.compile("^#(\\d+)(\\+?)$", Pattern.CASE_INSENSITIVE);

    private final MessagesService messagesService;

    @Autowired
    public ShowMessage(MessagesService messagesService) {
        this.messagesService = messagesService;
    }

    @Override
    public Pattern pattern() {
        return PATTERN;
    }

    @Override
    public String help() {
        return "#1234 - Show message (#1234+ - message with replies)";
    }

    @Override
    protected String execute(User sender, MessageListener protocolListener, String... arguments) {
        boolean showReplies = arguments[1].length() > 0;
        int mid = NumberUtils.toInt(arguments[0], 0);
        if (mid == 0) {
            return "Error";
        }
        Message msg = getMessagesService().getMessage(mid);
        if (msg != null) {
            if (showReplies) {
                List<Message> replies = getMessagesService().getReplies(mid);
                replies.add(0, msg);
                return String.join("\n", replies.stream().map(PlainTextFormatter::formatPost).collect(Collectors.toList()));
            }
            return PlainTextFormatter.formatPost(msg);
        }
        return "Message not found";
    }
}