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

import com.juick.User;
import com.juick.service.MessagesService;
import com.juick.service.SubscriptionService;
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.regex.Pattern;

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

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

    private final MessagesService messagesService;
    private final SubscriptionService subscriptionService;

    @Autowired
    public SubscribeMessage(MessagesService messagesService, SubscriptionService subscriptionService) {
        this.messagesService = messagesService;
        this.subscriptionService = subscriptionService;
    }

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

    @Override
    public String help() {
        return "S #1234 - subscribe to comments\nU #1234 - unsubscribe to comments";
    }

    @Override
    protected String execute(User sender, MessageListener protocolListener, String... arguments) {
        boolean subscribe = arguments[0].equalsIgnoreCase("s");
        int mid = NumberUtils.toInt(arguments[1], 0);
        if (getMessagesService().getMessage(mid) != null) {
            if (subscribe) {
                if (getSubscriptionService().subscribeMessage(mid, sender.getUid())) {
                    return "Subscribed";
                }
            } else {
                if (getSubscriptionService().unSubscribeMessage(mid, sender.getUid())) {
                    return "Unsubscribed from #" + mid;
                }
                return "You was not subscribed to #" + mid;
            }
        }
        return "Error";
    }
}