101 lines
2.5 KiB
Go
101 lines
2.5 KiB
Go
package priceiswrong
|
|
|
|
import (
|
|
"context"
|
|
"gitea/price-is-wrong/pkg/lib/db"
|
|
priceiswrong "gitea/price-is-wrong/pkg/state/priceiswrong/internal"
|
|
"html"
|
|
"math/rand"
|
|
)
|
|
|
|
func (p *PriceIsWrong) apply(e priceiswrong.Event) error {
|
|
switch e := e.(type) {
|
|
case *priceiswrong.Players:
|
|
p.Contestants = p.Contestants[:0]
|
|
for _, id := range e.IDs {
|
|
p.Contestants = append(p.Contestants, Player{ID: id})
|
|
}
|
|
if n := len(p.Contestants); n > 0 {
|
|
p.Host = p.Contestants[rand.Intn(n)].ID
|
|
}
|
|
case *priceiswrong.Host:
|
|
p.Host = e.ID
|
|
case *priceiswrong.Score:
|
|
for i := range p.Contestants {
|
|
if p.Contestants[i].ID == e.ID {
|
|
p.Contestants[i].Score += e.Score
|
|
}
|
|
}
|
|
case *priceiswrong.Item:
|
|
for i := range p.Contestants {
|
|
p.Contestants[i].Guess = ""
|
|
}
|
|
p.Item.ImageURL = e.ImageURL
|
|
p.Item.Title = html.EscapeString(e.Title)
|
|
p.Item.Description = html.EscapeString(e.Description)
|
|
p.Item.Value = html.EscapeString(e.Value)
|
|
case *priceiswrong.Guess:
|
|
for i := range p.Contestants {
|
|
if p.Contestants[i].ID == e.ID {
|
|
p.Contestants[i].Guess = html.EscapeString(e.Guess)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *PriceIsWrong) SetPlayers(ctx context.Context, ids []int) error {
|
|
return p.upsertEvent(ctx, &priceiswrong.Players{IDs: ids})
|
|
}
|
|
|
|
func (p *PriceIsWrong) SetHost(ctx context.Context, id int) error {
|
|
return p.upsertEvent(ctx, &priceiswrong.Host{ID: id})
|
|
}
|
|
|
|
func (p *PriceIsWrong) Score(ctx context.Context, id, score int) error {
|
|
return p.upsertEvent(ctx, &priceiswrong.Score{ID: id, Score: score})
|
|
}
|
|
|
|
func (p *PriceIsWrong) SetItem(ctx context.Context, imageURL, title, description, value string) error {
|
|
return p.upsertEvent(ctx, &priceiswrong.Item{
|
|
ImageURL: imageURL,
|
|
Title: title,
|
|
Description: description,
|
|
Value: value,
|
|
})
|
|
}
|
|
|
|
func (p *PriceIsWrong) Guess(ctx context.Context, id int, guess string) error {
|
|
return p.upsertEvent(ctx, &priceiswrong.Guess{
|
|
ID: id,
|
|
Guess: guess,
|
|
})
|
|
|
|
}
|
|
|
|
func (p *PriceIsWrong) upsertEvent(ctx context.Context, e priceiswrong.Event) error {
|
|
if err := upsertEvent(ctx, p.id, e); err != nil {
|
|
return err
|
|
}
|
|
|
|
p2, err := openID(ctx, p.id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
*p = *p2
|
|
return nil
|
|
}
|
|
|
|
func upsertEvent(ctx context.Context, priceIsWrongID int, e priceiswrong.Event) error {
|
|
b, err := priceiswrong.MarshalEvent(e)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = db.From(ctx).ExecContext(ctx, `
|
|
INSERT INTO priceiswrong_events (priceiswrong_id, payload) VALUES (?, ?)
|
|
`, priceIsWrongID, b)
|
|
return err
|
|
}
|