diff --git a/src/state/fsm/priceiswrong/events.go b/src/state/fsm/priceiswrong/events.go index b9bf9bb..a33355e 100644 --- a/src/state/fsm/priceiswrong/events.go +++ b/src/state/fsm/priceiswrong/events.go @@ -4,11 +4,11 @@ import ( "context" "gitea/price-is-wrong/src/lib/db" priceiswrong "gitea/price-is-wrong/src/state/fsm/priceiswrong/internal" - "io" + "math/rand" ) -func (p *PriceIsWrong) TODO(ctx context.Context, id int) error { - return io.EOF +func (p *PriceIsWrong) Players(ctx context.Context, ids []int) error { + return p.upsertEvent(ctx, &priceiswrong.Players{IDs: ids}) } func (p *PriceIsWrong) upsertEvent(ctx context.Context, e priceiswrong.Event) error { @@ -39,8 +39,14 @@ func upsertEvent(ctx context.Context, priceIsWrongID int, e priceiswrong.Event) func (p *PriceIsWrong) apply(e priceiswrong.Event) error { switch e := e.(type) { - case *int: - _ = e + 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 + } } return nil } diff --git a/src/state/fsm/priceiswrong/internal/event.go b/src/state/fsm/priceiswrong/internal/event.go index 25ede72..7ff1ee8 100644 --- a/src/state/fsm/priceiswrong/internal/event.go +++ b/src/state/fsm/priceiswrong/internal/event.go @@ -7,9 +7,13 @@ import ( type Event interface{} +type Players struct { + IDs []int +} + func ParseEvent(b []byte) (Event, error) { typesToPointers := map[string]any{ - "*any": &b, + "*priceiswrong.Players": &Players{}, } t, err := event.Parse(b, typesToPointers) return typesToPointers[t], err diff --git a/src/state/fsm/priceiswrong/open.go b/src/state/fsm/priceiswrong/open.go index 546482f..e86eaaa 100644 --- a/src/state/fsm/priceiswrong/open.go +++ b/src/state/fsm/priceiswrong/open.go @@ -11,7 +11,7 @@ import ( type PriceIsWrong struct { id int Host int - Contestants Player + Contestants []Player } type Player struct { diff --git a/src/state/fsm/priceiswrong/priceiswrong_test.go b/src/state/fsm/priceiswrong/priceiswrong_test.go new file mode 100644 index 0000000..79f8fb0 --- /dev/null +++ b/src/state/fsm/priceiswrong/priceiswrong_test.go @@ -0,0 +1,24 @@ +package priceiswrong_test + +import ( + "gitea/price-is-wrong/src/lib" + "gitea/price-is-wrong/src/state/fsm/priceiswrong" + "testing" +) + +func TestPriceIsWrong(t *testing.T) { + ctx := lib.NewTestCtx(t) + + p, err := priceiswrong.Open(ctx, "name") + if err != nil { + t.Fatal(err) + } + + if err := p.Players(ctx, []int{4, 5, 6}); err != nil { + t.Fatal(err) + } else if len(p.Contestants) != 3 { + t.Errorf("bad contestants: %+v", p.Contestants) + } else if p.Host < 4 || p.Host > 6 { + t.Errorf("bad host: %+v", p.Host) + } +}