/*
Implements some additional prometheus metrics that we need for privacy preserving
counts of users and proxies
*/

package safeprom

import (
	"sync/atomic"

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
	"google.golang.org/protobuf/proto"
)

// New Prometheus counter type that produces rounded counts of metrics
// for privacy preserving reasons
type Counter interface {
	prometheus.Metric

	Inc()
}

type counter struct {
	total uint64 //reflects the true count
	value uint64 //reflects the rounded count

	desc       *prometheus.Desc
	labelPairs []*dto.LabelPair
}

// Implements the Counter interface
func (c *counter) Inc() {
	atomic.AddUint64(&c.total, 1)
	if c.total > c.value {
		atomic.AddUint64(&c.value, 8)
	}
}

// Implements the prometheus.Metric interface
func (c *counter) Desc() *prometheus.Desc {
	return c.desc
}

// Implements the prometheus.Metric interface
func (c *counter) Write(m *dto.Metric) error {
	m.Label = c.labelPairs

	m.Counter = &dto.Counter{Value: proto.Float64(float64(c.value))}
	return nil
}

// New prometheus vector type that will track Counter metrics
// accross multiple labels
type CounterVec struct {
	*prometheus.MetricVec
}

// NewCounterVec will create a CounterVec but will not register it, users must register it themselves.
// The behaviour of this function is similar to github.com/prometheus/client_golang/prometheus
func NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *CounterVec {
	desc := prometheus.NewDesc(
		prometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
		opts.Help,
		labelNames,
		opts.ConstLabels,
	)
	c := &CounterVec{
		MetricVec: prometheus.NewMetricVec(desc, func(lvs ...string) prometheus.Metric {
			if len(lvs) != len(labelNames) {
				panic("inconsistent cardinality")
			}
			return &counter{desc: desc, labelPairs: prometheus.MakeLabelPairs(desc, lvs)}
		}),
	}
	return c
}

// NewCounterVecRegistered will create a CounterVec and register it.
// The behaviour of this function is similar to github.com/prometheus/client_golang/prometheus/promauto
func NewCounterVecRegistered(opts prometheus.CounterOpts, labelNames []string) *CounterVec {
	c := NewCounterVec(opts, labelNames)
	prometheus.DefaultRegisterer.MustRegister(c)
	return c
}

// Helper function to return the underlying Counter metric from MetricVec
func (v *CounterVec) With(labels prometheus.Labels) Counter {
	metric, err := v.GetMetricWith(labels)
	if err != nil {
		panic(err)
	}
	return metric.(Counter)
}

// Helper function to return the underlying Counter metric from MetricVec
func (v *CounterVec) WithLabelValues(lvs ...string) Counter {
	metric, err := v.GetMetricWithLabelValues(lvs...)
	if err != nil {
		panic(err)
	}
	return metric.(Counter)
}
