package safeprom

import (
	"bufio"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func TestIncVecWithLabelValues(t *testing.T) {
	ts := httptest.NewServer(promhttp.Handler())
	defer ts.Close()

	metricName := "label_values"
	usersTotal := NewCounterVecRegistered(
		prometheus.CounterOpts{
			Name: metricName,
		},
		[]string{"status"},
	)

	for i := 0; i < 8; i++ {
		usersTotal.WithLabelValues("active").Inc()
		expectedValue(t, ts.URL, metricName, 8)
	}

	usersTotal.WithLabelValues("active").Inc()
	expectedValue(t, ts.URL, metricName, 16)
}

func TestIncVecWith(t *testing.T) {
	ts := httptest.NewServer(promhttp.Handler())
	defer ts.Close()

	metricName := "with"
	usersTotal := NewCounterVecRegistered(
		prometheus.CounterOpts{
			Name: metricName,
		},
		[]string{"status"},
	)

	for i := 0; i < 8; i++ {
		usersTotal.With(prometheus.Labels{"status": "active"}).Inc()
		expectedValue(t, ts.URL, metricName, 8)
	}

	usersTotal.With(prometheus.Labels{"status": "active"}).Inc()
	expectedValue(t, ts.URL, metricName, 16)
}

func expectedValue(t *testing.T, url string, metric string, expected int) {
	res, err := http.Get(url)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()

	value := -1
	scanner := bufio.NewScanner(res.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.HasPrefix(line, metric) {
			continue
		}
		parts := strings.Split(line, " ")
		value, err = strconv.Atoi(parts[len(parts)-1])
		if err != nil {
			t.Fatal(err)
		}
	}

	if value == -1 {
		t.Fatal("Metric", metric, "was not present")
	}

	if value != expected {
		t.Error("Metric value is not", expected, ":", value)
	}
}
