// Copyright (C) 2020 Emanuele Rocca <ema@wikimedia.org>
// Copyright (C) 2020 Wikimedia Foundation, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package promrdkafka

import (
	"io/ioutil"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/stretchr/testify/assert"
)

func TestNew(t *testing.T) {
	m := NewMetrics()
	assert.Empty(t, m.values)
}

func TestUpdateBadJSON(t *testing.T) {
	m := NewMetrics()
	err := m.Update("banana potato nah")
	assert.Error(t, err)
}

func TestUpdateValidJSONCannotUnmarshal(t *testing.T) {
	m := NewMetrics()
	err := m.Update(`[ "banana", "potato" ]`)
	assert.Error(t, err)
}

func TestUpdateGoodJSON(t *testing.T) {
	m := NewMetrics()
	err := m.Update(`{ "name": "atskafka#producer-1", "client_id": "atskafka", "type": "producer" }`)
	assert.NoError(t, err)
	assert.NotNil(t, m.values["rdkafka_producer_tx"])

	err = m.Update(`{ "name": "atskafka#consumer-1", "client_id": "atskafka", "type": "consumer" }`)
	assert.NoError(t, err)
	assert.NotNil(t, m.values["rdkafka_consumer_tx"])
}

func updateFromFilename(t *testing.T, filename string) *Metrics {
	kafkaStats, err := ioutil.ReadFile(filename)
	assert.NoError(t, err)

	m := NewMetrics()
	err = m.Update(string(kafkaStats))
	assert.NoError(t, err)
	return m
}

func TestUpdateMinimal(t *testing.T) {
	updateFromFilename(t, "fixtures/minimal.json")
}

func TestUpdateProducer(t *testing.T) {
	updateFromFilename(t, "fixtures/producer.json")
}

func TestUpdateConsumer(t *testing.T) {
	updateFromFilename(t, "fixtures/consumer.json")
}

func TestLabels(t *testing.T) {
	m := updateFromFilename(t, "fixtures/producer.json")

	l := prometheus.Labels{"client_id": "atskafka",
		"topics":     "atskafka_test_webrequest_text",
		"partitions": "1"}

	_, err := m.values["rdkafka_producer_topics_partitions_txmsgs"].GetMetricWith(l)

	assert.NoError(t, err)
}
