forked from tucnak/telebot
/
fsm_context.go
62 lines (46 loc) · 1.15 KB
/
fsm_context.go
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
package telebot
import (
"fmt"
)
type StateContextID int64
type StateContext struct {
id StateContextID
currentState *State
storage IStorage
}
func NewStateContext(id StateContextID,
currentState *State,
storage IStorage) *StateContext {
return &StateContext{id: id, currentState: currentState, storage: storage}
}
func AcquireStateContext(id StateContextID,
stateGroup *stateGroup,
storage IStorage) (*StateContext, error) {
stateContext, err := storage.AcquireContext(id, stateGroup)
return stateContext, err
}
func (sc *StateContext) HandleInput(c Context) error {
contextStorage, err := sc.storage.ContextStorage(sc.id)
if err != nil || contextStorage == nil {
fmt.Printf("storage not init")
return err
}
nextState, err := sc.currentState.HandleInput(c, contextStorage)
if err != nil {
return err
}
if nextState != nil {
err = sc.ChangeState(sc.id, nextState)
if err == nil {
nextState.Greet(c, contextStorage)
}
}
return err
}
func (sc *StateContext) ChangeState(id StateContextID, state *State) error {
err := sc.storage.ChangeState(id, state)
if err == nil {
sc.currentState = state
}
return err
}