aboutsummaryrefslogtreecommitdiff
path: root/user/xp.go
blob: ca0825848a146f54516f52595fc637bdaa0fad8a (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
package user

import (
	"context"
	"slices"
	"time"

	"git.anhgelus.world/anhgelus/les-copaings-bot/exp"
	"github.com/nyttikord/gokord/bot"
	"github.com/nyttikord/gokord/user"
)

type cXP struct {
	Cxp     uint
	copaing *Copaing
}

func (c *cXP) Copaing() *Copaing {
	return c.copaing
}

func (c *cXP) GetXP() uint {
	return c.Cxp
}

func (cc *CopaingCached) AddXP(ctx context.Context, s bot.Session, m *user.Member, xp uint, fn func(uint, uint)) {
	old := cc.XP
	pastLevel := exp.Level(old)
	bot.Logger(ctx).Debug("adding xp", "user", m.DisplayName(), "old", old, "to add", xp)
	cc.XP += xp
	cc.XPToAdd += xp
	if err := cc.Save(ctx); err != nil {
		bot.Logger(ctx).Error(
			"saving user in state",
			"error", err, "user", m.DisplayName(), "xp", xp, "guild", cc.GuildID,
		)
		return
	}
	newLevel := exp.Level(old + xp)
	if newLevel > pastLevel {
		fn(old+xp, newLevel)
		onNewLevel(ctx, s, m, newLevel)
	}
}

func (cc *CopaingCached) GetXPForDays(d int) uint {
	xp := uint(0)
	for _, v := range cc.XPs {
		if v.Time <= time.Duration(d*24)*time.Hour {
			xp += v.XP
		}
	}
	return xp + cc.XPToAdd
}

// GetBestXP returns n Copaings with the best XP within d days (d <= cfg.DaysXPRemain; d < 0 <=> d = cfg.DaysXPRemain)
func GetBestXP(ctx context.Context, guildId string, n uint, d int) []CopaingCached {
	ccs := GetState(ctx).Copaings(guildId)
	if d > 0 {
		for i, cc := range ccs {
			cc.XP = cc.GetXPForDays(d)
			ccs[i] = cc
		}
	}
	slices.SortFunc(ccs, func(a, b CopaingCached) int {
		// desc order
		return int(b.XP) - int(a.XP)
	})
	return ccs[:min(len(ccs), int(n))]
}