package inbox

import "sync"

type Inbox struct {
	mutex    *sync.Mutex
	signalCh chan struct{}
	items    []any
}

func New() *Inbox {
	return &Inbox{
		mutex:    new(sync.Mutex),
		signalCh: make(chan struct{}, 1),
	}
}

func (s *Inbox) Ready() chan struct{} {
	return s.signalCh
}

func (s *Inbox) Push(x any) {
	s.mutex.Lock()
	s.items = append(s.items, x)
	s.mutex.Unlock()
	select {
	case s.signalCh <- struct{}{}:
	default:
	}
}

func (s *Inbox) Drain() []any {
	s.mutex.Lock()
	items := s.items
	s.items = nil
	s.mutex.Unlock()
	return items
}
