package metrics

import (
	"time"

	telemetry "code.justin.tv/amzn/TwitchTelemetry"
	cw "code.justin.tv/amzn/TwitchTelemetryCloudWatchMetricsSender"
	"code.justin.tv/eventbus/fultonlog"
	"go.uber.org/zap"
)

const (
	flushPeriod       = 30 * time.Second
	bufferSize        = 100000
	aggregationPeriod = time.Minute
)

var observer telemetry.SampleObserver

type noopObs struct{}

func (no *noopObs) ObserveSample(s *telemetry.Sample) {}
func (no *noopObs) Flush()                            {}
func (no *noopObs) Stop()                             {}

func init() {
	observer = &noopObs{}
}

// InitializeMetrics instantiates the global observer singleton as a CloudWatch
// buffered aggregator
func InitializeMetrics(l *zap.Logger) {
	fultonLogger := fultonlog.FromZapLogger(l)
	// We want to make a singleton here because we want to make as few CloudWatch
	// calls as we can, opting to aggregate them all together
	procID := ProcessIdentifier()
	sender := cw.NewUnbuffered(&procID, fultonLogger)
	observer = telemetry.NewBufferedAggregator(flushPeriod, bufferSize, aggregationPeriod, sender, fultonLogger)
}

// Observer returns the global buffered metrics observer singleton
func Observer() telemetry.SampleObserver {
	return observer
}
