package statsdclient

import (
	"time"

	identifier "code.justin.tv/amzn/TwitchProcessIdentifier"
	telemetry "code.justin.tv/amzn/TwitchTelemetry"
	statsdSender "code.justin.tv/amzn/TwitchTelemetryStatsdMetricsSender"
	"code.justin.tv/sse/malachai/pkg/config"
	"code.justin.tv/sse/malachai/pkg/internal/stats"
	"code.justin.tv/sse/malachai/pkg/internal/stats/statsiface"
)

// NewReporter returns a telemetry reporter backed by statsdSender.
// If noop is set - noop reporter is returned. otherwise
// statsd reporter with endpoint "statsd.central.twitch.a2z.com:8125" is returned.
func NewReporter(environment, serviceName string, noop bool) (statsiface.ReporterAPI, error) {
	if noop {
		return &stats.NoopReporter{}, nil
	}

	resources, err := config.GetResources(environment)
	if err != nil {
		return nil, err
	}
	tPid := &identifier.ProcessIdentifier{
		Service:  serviceName,
		Stage:    environment,
		Substage: "primary",
		Region:   resources.Region,
	}

	sender, err := statsdSender.NewUnbuffered(tPid, "statsd.central.twitch.a2z.com:8125", nil)
	if err != nil {
		return nil, err
	}
	twitchTelemetryCloudwatchFlushPeriod := 1 * time.Minute
	twitchTelemetryCloudwatchAggregatePeriod := 30 * time.Second

	sampleObserver := telemetry.NewBufferedAggregator(twitchTelemetryCloudwatchFlushPeriod, 10000, twitchTelemetryCloudwatchAggregatePeriod, sender, nil)
	return &telemetry.SampleReporter{
		SampleBuilder:  telemetry.SampleBuilder{ProcessIdentifier: *tPid},
		SampleObserver: sampleObserver,
	}, nil
}
