package metrics

import (
	"strconv"
	"time"

	"git.frostfs.info/TrueCloudLab/frostfs-observability/metrics"
	"github.com/prometheus/client_golang/prometheus"
)

// InnerRingServiceMetrics contains metrics collected by inner ring.
type InnerRingServiceMetrics struct {
	epoch             prometheus.Gauge
	health            prometheus.Gauge
	eventDuration     *prometheus.HistogramVec
	morphCacheMetrics *morphCacheMetrics
}

// NewInnerRingMetrics returns new instance of metrics collectors for inner ring.
func NewInnerRingMetrics() *InnerRingServiceMetrics {
	var (
		epoch = metrics.NewGauge(prometheus.GaugeOpts{
			Namespace: innerRingNamespace,
			Subsystem: innerRingSubsystem,
			Name:      "epoch",
			Help:      "Current epoch as seen by inner-ring node.",
		})
		health = metrics.NewGauge(prometheus.GaugeOpts{
			Namespace: innerRingNamespace,
			Subsystem: innerRingSubsystem,
			Name:      "health",
			Help:      "Current inner-ring node state.",
		})
		eventDuration = metrics.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: innerRingNamespace,
			Subsystem: innerRingSubsystem,
			Name:      "event_duration_seconds",
			Help:      "Duration of processing of inner-ring events",
		}, []string{typeLabel, successLabel})
	)

	return &InnerRingServiceMetrics{
		epoch:             epoch,
		health:            health,
		eventDuration:     eventDuration,
		morphCacheMetrics: newMorphCacheMetrics(innerRingNamespace),
	}
}

// SetEpoch updates epoch metrics.
func (m *InnerRingServiceMetrics) SetEpoch(epoch uint64) {
	m.epoch.Set(float64(epoch))
}

// SetHealth updates health metrics.
func (m *InnerRingServiceMetrics) SetHealth(s int32) {
	m.health.Set(float64(s))
}

func (m *InnerRingServiceMetrics) AddEvent(d time.Duration, typ string, success bool) {
	m.eventDuration.With(prometheus.Labels{
		typeLabel:    typ,
		successLabel: strconv.FormatBool(success),
	}).Observe(d.Seconds())
}

func (m *InnerRingServiceMetrics) MorphCacheMetrics() MorphCacheMetrics {
	return m.morphCacheMetrics
}