package configuration

import (
	"fmt"
	"log"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/getsentry/sentry-go"
)

type ChangeNotifier struct {
	channels []chan<- Configuration
	hub      *sentry.Hub
}

func NewChangeNotifier() *ChangeNotifier {
	return &ChangeNotifier{
		channels: make([]chan<- Configuration, 0),
		hub:      sentry.CurrentHub().Clone(),
	}
}

func (p *ChangeNotifier) Close() {
	p.hub.Flush(10 * time.Second)
}

func (p *ChangeNotifier) Subscribe(ch chan<- Configuration) {
	p.channels = append(p.channels, ch)
}

func (p *ChangeNotifier) Notify(config Configuration) {
	for _, ch := range p.channels {
		select {
		case ch <- config:

		default:
			err := fmt.Errorf("channel overflow on a ChangeNotifier notification channel")
			p.hub.CaptureException(err)
			log.Print(err)
		}
	}
}

func (p *ChangeNotifier) OnConfigChange(in fsnotify.Event) {
	log.Print("Reloading configuration")
	config := LoadConfiguration()
	p.Notify(config)
}
