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) {
	//fmt.Printf("inbox.Push: %#v\n", x)
	s.mutex.Lock()
	s.items = append(s.items, x)
	s.mutex.Unlock()
	//fmt.Printf("inbox.Pushed\n")
	select {
	case s.signalCh <- struct{}{}:
	default:
	}
}

func (s *Inbox) Drain() []any {
	//fmt.Printf("inbox.Drain\n")
	s.mutex.Lock()
	items := s.items
	s.items = nil
	s.mutex.Unlock()
	//fmt.Printf("inbox.Drained: %#v\n", items)
	return items
}
