package stat

import (
	"sync"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/cloudwatch"
)

// value of a metric stored as various statistics. this collapses all useful
// statistics that are bucketable
type statisticSet struct {
	initSync    sync.Once
	sum         float64
	sampleCount int64
	minimum     float64
	maximum     float64
}

func (s *statisticSet) init(initialValue float64) {
	s.initSync.Do(func() {
		s.minimum = initialValue
		s.maximum = initialValue
	})
}

func (s *statisticSet) Increment() {
	s.Record(1.0)
}

func (s *statisticSet) Record(value float64) {
	s.init(value)

	s.sum += value
	s.sampleCount++
	if value < s.minimum {
		s.minimum = value
	}

	if value > s.maximum {
		s.maximum = value
	}
}

func (s *statisticSet) StatisticSet() *cloudwatch.StatisticSet {
	return &cloudwatch.StatisticSet{
		Maximum:     aws.Float64(s.maximum),
		Minimum:     aws.Float64(s.minimum),
		SampleCount: aws.Float64(float64(s.sampleCount)),
		Sum:         aws.Float64(s.sum),
	}
}
