Passed
Push — master ( a32b8b...b8f7a7 )
by Viktor
02:03 queued 11s
created

cmd.pollVote   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 1
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
package cmd
2
3
import (
4
	"fmt"
5
	"strconv"
6
	"strings"
7
8
	"github.com/FlameInTheDark/dtbot/bot"
9
)
10
11
// PollCommand handle polls commands
12
func PollCommand(ctx bot.Context) {
13
	if len(ctx.Args) == 0 {
14
		return
15
	}
16
	switch ctx.Args[0] {
17
	case "new":
18
		pollNew(&ctx)
19
	case "vote":
20
		pollVote(&ctx)
21
	case "end":
22
		pollEnd(&ctx)
23
	}
24
}
25
26
func pollNew(ctx *bot.Context) {
27
	ctx.MetricsCommand("poll", "new")
28
	err := ctx.Data.CreatePoll(ctx, strings.Split(strings.Join(ctx.Args[1:], " "), "|"))
29
	if err != nil {
30
		ctx.ReplyEmbed(ctx.Loc("polls"), err.Error())
31
		return
32
	}
33
	fields := strings.Split(strings.Join(ctx.Args[1:], " "), "|")
34
	for key, val := range fields {
35
		fields[key] = fmt.Sprintf("%v: %v", key+1, val)
36
	}
37
	ctx.ReplyEmbed(ctx.Loc("polls"), fmt.Sprintf("%v:\n%v", ctx.Loc("polls_created"), strings.Join(fields, "\n")))
38
}
39
40
func pollVote(ctx *bot.Context) {
41
	ctx.MetricsCommand("poll", "vote")
42
	val, err := strconv.Atoi(ctx.Args[1])
43
	if err != nil {
44
		ctx.ReplyEmbed(ctx.Loc("polls"), ctx.Loc("polls_wrong_field"))
45
		return
46
	}
47
	verr := ctx.Data.AddPollVote(ctx, val)
48
	if verr != nil {
49
		ctx.ReplyEmbed(ctx.Loc("polls"), verr.Error())
50
		return
51
	}
52
}
53
54
func pollEnd(ctx *bot.Context) {
55
	ctx.MetricsCommand("poll", "end")
56
	result, err := ctx.Data.EndPoll(ctx)
57
	if err != nil {
58
		ctx.ReplyEmbed(ctx.Loc("polls"), err.Error())
59
		return
60
	}
61
	var newResults []string
62
	for name, count := range result {
63
		newResults = append(newResults, fmt.Sprintf("[%v] %v", count, name))
64
	}
65
	ctx.ReplyEmbed(ctx.Loc("polls"), fmt.Sprintf("%v:\n%v", ctx.Loc("polls_ends"), strings.Join(newResults, "\n")))
66
}