72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
|
|
package machine
|
|
|
|
import (
|
|
"errors"
|
|
)
|
|
|
|
type State string
|
|
|
|
type Stater interface {
|
|
AddStates(name ...State)
|
|
GetState(name string) State
|
|
AddTransition(trigger string, source []State, dest State)
|
|
AddSubscription(transition string, subscription Subscriber) error
|
|
AddModel(m Modeler)
|
|
Trigger(transition string) error
|
|
CurrentState() State
|
|
}
|
|
|
|
type Definition struct {
|
|
states []State
|
|
triggers map[string]Transitioner
|
|
model Modeler
|
|
}
|
|
|
|
func New(initial State) Stater {
|
|
return &Definition{model: NewModel(initial), triggers: make(map[string]Transitioner)}
|
|
}
|
|
|
|
func States(name ...State) []State {
|
|
return name
|
|
}
|
|
|
|
func (d *Definition) AddStates(name ...State) {
|
|
d.states = append(d.states, name...)
|
|
}
|
|
|
|
func (d *Definition) AddTransition(trigger string, source []State, dest State) {
|
|
d.triggers[trigger] = NewTransition(trigger, source, dest)
|
|
}
|
|
|
|
func (d *Definition) GetState(name string) State {
|
|
var r State
|
|
for _, s := range d.states {
|
|
if string(s) == name {
|
|
return s
|
|
}
|
|
}
|
|
return r
|
|
}
|
|
|
|
func (d *Definition) AddModel(m Modeler) {
|
|
d.model = m
|
|
}
|
|
|
|
func (d *Definition) Trigger(transition string) error {
|
|
return d.triggers[transition].Run(d.model)
|
|
}
|
|
|
|
func (d *Definition) CurrentState() State {
|
|
return d.model.InspectState()
|
|
}
|
|
|
|
func (d *Definition) AddSubscription(transition string, subscription Subscriber) error {
|
|
if t, ok := d.triggers[transition]; ok {
|
|
t.Subscribe(subscription)
|
|
return nil
|
|
}
|
|
return errors.New("Transition does not exist")
|
|
}
|