aboutsummaryrefslogtreecommitdiff
path: root/commands/stats.go
blob: e464890cadda780ba6e2b74b23571bc5a4944668 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package commands

import (
	"bytes"
	"image/color"
	"math"
	"math/rand/v2"
	"slices"
	"time"

	"git.anhgelus.world/anhgelus/les-copaings-bot/config"
	"git.anhgelus.world/anhgelus/les-copaings-bot/exp"
	"git.anhgelus.world/anhgelus/les-copaings-bot/user"
	"github.com/anhgelus/gokord"
	"github.com/anhgelus/gokord/cmd"
	"github.com/anhgelus/gokord/logger"
	"github.com/bwmarrin/discordgo"
	"github.com/jackc/pgx/v5/pgtype"
	"gonum.org/v1/plot"
	"gonum.org/v1/plot/plotter"
	"gonum.org/v1/plot/vg"
)

type data struct {
	CreatedAt time.Time
	XP        int
	CopaingID int
}

type dbData struct {
	CreatedAt *pgtype.Date
	XP        int
	CopaingID int
}

func Stats(s *discordgo.Session, i *discordgo.InteractionCreate, opt cmd.OptionMap, resp *cmd.ResponseBuilder) {
	cfg := config.GetGuildConfig(i.GuildID)
	days := cfg.DaysXPRemains
	if v, ok := opt["days"]; ok {
		in := v.IntValue()
		if in < 0 || uint(in) > days {
			if err := resp.SetMessage("Nombre de jours invalide").IsEphemeral().Send(); err != nil {
				logger.Alert("commands/stats.go - Sending invalid days", err.Error())
			}
			return
		}
		days = uint(in)
	}
	var rawData []*data
	if gokord.Debug {
		var rawCopaingData []*user.CopaingXP
		err := gokord.DB.
			Where("guild_id = ? and created_at > ?", i.GuildID, exp.TimeStampNDaysBefore(days)).
			Find(&rawCopaingData).
			Error
		if err != nil {
			logger.Alert("commands/stats.go - Fetching result", err.Error())
			return
		}
		rawData = make([]*data, len(rawCopaingData))
		for in, d := range rawCopaingData {
			rawData[in] = &data{
				CreatedAt: d.CreatedAt,
				XP:        int(d.XP),
				CopaingID: int(d.CopaingID),
			}
		}
	} else {
		sql := `SELECT "created_at"::date::text, sum("xp") as xp, "copaing_id" FROM copaing_xps WHERE "guild_id" = ? and "created_at" > ? GROUP BY "created_at"::date, "copaing_id"`
		var rawDbData []dbData
		res := gokord.DB.Raw(sql, i.GuildID, exp.TimeStampNDaysBefore(days))
		if err := res.Scan(&rawDbData).Error; err != nil {
			logger.Alert("commands/stats.go - Fetching result", err.Error())
			return
		}
		rawData = make([]*data, len(rawDbData))
		for in, d := range rawDbData {
			rawData[in] = &data{
				CreatedAt: d.CreatedAt.Time,
				XP:        d.XP,
				CopaingID: d.CopaingID,
			}
		}
	}

	copaings := map[int]*user.Copaing{}
	stats := map[int]*[]plotter.XY{}

	for _, raw := range rawData {
		_, ok := copaings[raw.CopaingID]
		if !ok {
			var cp user.Copaing
			if err := gokord.DB.First(&cp, raw.CopaingID).Error; err != nil {
				logger.Alert("commands/stats.go - Finding copaing", err.Error(), "id", raw.CopaingID)
				return
			}
			copaings[raw.CopaingID] = &cp
		}
		pts, ok := stats[raw.CopaingID]
		if !ok {
			pts = &[]plotter.XY{}
			stats[raw.CopaingID] = pts
		}
		t := float64(raw.CreatedAt.Unix() - time.Now().Unix())
		if !gokord.Debug {
			t = math.Ceil(t / (24 * 60 * 60))
		}
		*pts = append(*pts, plotter.XY{
			X: t,
			Y: float64(raw.XP),
		})
	}

	p := plot.New()
	p.Title.Text = "Évolution de l'XP"
	p.X.Label.Text = "Jours"
	p.Y.Label.Text = "XP"

	p.Add(plotter.NewGrid())

	r := rand.New(rand.NewPCG(uint64(time.Now().Unix()), uint64(time.Now().Unix())))
	for in, c := range copaings {
		m, err := s.GuildMember(i.GuildID, c.DiscordID)
		if err != nil {
			logger.Alert("commands/stats.go - Fetching guild member", err.Error())
			return
		}
		slices.SortFunc(*stats[in], func(a, b plotter.XY) int {
			if a.X < b.X {
				return -1
			}
			if a.X > b.X {
				return 1
			}
			return 0
		})
		first := (*stats[in])[0]
		if first.X > float64(-days) {
			*stats[in] = append([]plotter.XY{{
				X: first.X - 1, Y: 0,
			}}, *stats[in]...)
		}
		last := (*stats[in])[len(*stats[in])-1]
		if last.X <= -1 {
			*stats[in] = append(*stats[in], plotter.XY{
				X: last.X + 1, Y: 0,
			})
		}
		l, err := plotter.NewLine(plotter.XYs(*stats[in]))
		if err != nil {
			logger.Alert("commands/stats.go - Adding line points", err.Error())
			return
		}
		l.LineStyle.Width = vg.Points(1)
		l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
		l.LineStyle.Color = color.RGBA{R: uint8(r.UintN(255)), G: uint8(r.UintN(255)), B: uint8(r.UintN(255)), A: 255}
		p.Add(l)
		p.Legend.Add(m.DisplayName(), l)
	}
	w, err := p.WriterTo(8*vg.Inch, 6*vg.Inch, "png")
	if err != nil {
		logger.Alert("commands/stats.go - Generating png", err.Error())
		return
	}
	b := new(bytes.Buffer)
	_, err = w.WriteTo(b)
	if err != nil {
		logger.Alert("commands/stats.go - Writing png", err.Error())
	}
	err = resp.AddFile(&discordgo.File{
		Name:        "plot.png",
		ContentType: "image/png",
		Reader:      b,
	}).Send()
	if err != nil {
		logger.Alert("commands/stats.go - Sending response", err.Error())
	}
}