package tins2020

func NewEvents() *Events {
	return &Events{events: map[int]EventInterfaceFn{}}
}

type Events struct {
	nextID int
	events map[int]EventInterfaceFn
}

type EventHandler interface {
	Register(EventFn) int
	RegisterItf(EventInterfaceFn) int
	Unregister(int)
}

func (h *Events) Notify(state interface{}) {
	for _, event := range h.events {
		event(state)
	}
}

func (h *Events) Register(fn EventFn) int { return h.RegisterItf(func(interface{}) { fn() }) }

func (h *Events) RegisterItf(fn EventInterfaceFn) int {
	id := h.nextID
	h.nextID++
	h.events[id] = fn
	return id
}

func (h *Events) Unregister(id int) { delete(h.events, id) }