package telemetry

import (
	"errors"
	"io"
	"time"
)

// SampleReportingWriter reports telemetry samples for each write.
type SampleReportingWriter struct {
	Writer                 io.Writer
	Reporter               *SampleReporter
	BytesWrittenMetricName string
	DurationMetricName     string
}

// Write writes data and reports a metric.
func (w *SampleReportingWriter) Write(p []byte) (int, error) {
	if w.Writer == nil {
		return 0, errors.New("unable to write: no Writer was configured")
	}

	start := time.Now()
	n, err := w.Writer.Write(p)
	if w.Reporter != nil {
		w.Reporter.ReportDurationSample(w.DurationMetricName, time.Now().Sub(start))
		w.Reporter.Report(w.BytesWrittenMetricName, float64(n), UnitBytes)
	}
	return n, err
}
