package statsrunner

import (
	"sync"

	"code.justin.tv/sse/malachai/pkg/internal/stats"
)

type incrementableMetricValues struct {
	values     map[string]*stats.IncrementableMetricCount
	valuesLock sync.Locker
}

func (imv *incrementableMetricValues) Increment(im *IncrementableMetric) (err error) {
	imv.valuesLock.Lock()
	defer imv.valuesLock.Unlock()

	key, err := im.toKey()
	if err != nil {
		return
	}

	if value, ok := imv.values[key]; ok {
		value.Count++
	} else {
		imv.values[key] = &stats.IncrementableMetricCount{Metric: im.IncrementableMetric, Count: 1}
	}

	return
}

func (imv *incrementableMetricValues) PopValues() (values []*stats.IncrementableMetricCount) {
	imv.valuesLock.Lock()
	currentValues := imv.values
	imv.values = make(map[string]*stats.IncrementableMetricCount)
	imv.valuesLock.Unlock()

	values = make([]*stats.IncrementableMetricCount, 0, len(currentValues))
	for _, value := range currentValues {
		values = append(values, value)
	}
	return
}
