package status

import (
	"fmt"
	"image/color"
)

// Meter types

type Meter struct {
	Label string
	Base  float64
	Level float64
	Color color.NRGBA
}

type Config struct {
	Label string
	Base  float64
	Color color.NRGBA
}

// Meter manager

type Manager struct {
	meters []Meter
}

func NewManager(cfgs []Config) *Manager {
	meters := make([]Meter, len(cfgs))
	for i, cfg := range cfgs {
		meters[i] = Meter{
			Label: safeLabel(cfg.Label, i),
			Base:  clamp(cfg.Base, 0, 100),
			Level: clamp(cfg.Base, 0, 100),
			Color: nonTransparent(cfg.Color),
		}
	}

	return &Manager{meters: meters}
}

func (m *Manager) Update() {
	for i := range m.meters {
		m.meters[i].Level = m.meters[i].Base
	}
}

func (m *Manager) Meters() []Meter {
	out := make([]Meter, len(m.meters))
	copy(out, m.meters)
	return out
}

// Helper functions

func clamp(value, min, max float64) float64 {
	if value < min {
		return min
	}
	if value > max {
		return max
	}
	return value
}

func safeLabel(label string, fallback int) string {
	if label == "" {
		return fmt.Sprintf("Meter %d", fallback+1)
	}
	return label
}

func nonTransparent(c color.NRGBA) color.NRGBA {
	if c.A == 0 {
		c.A = 255
	}
	return c
}
