package memcache

import (
	"crypto/rand"
	"sort"
	"testing"
)

var keys []string

func init() {
	b := make([]byte, 64)
	for i := 0; i < 100000; i++ {
		_, err := rand.Read(b)
		if err != nil {
			panic(err)
		}
		keys = append(keys, string(b))
	}
}

func validateDistribution(t *testing.T, ring *HashRing, nodes []string) {
	weights := map[string]int{}
	for _, node := range nodes {
		weights[node]++
	}

	choices := map[string]int{}
	for _, key := range keys {
		node, _ := ring.GetNode(key)
		choices[node]++
	}

	normalized := []int{}
	for k, c := range choices {
		normalized = append(normalized, c/weights[k])
	}

	sort.Ints(normalized)

	expected := (len(keys) / len(nodes)) / 10 // 10% drift
	got := normalized[len(normalized)-1] - normalized[0]
	if got > expected {
		t.Errorf("The drift between number of keys on each server is greater than 10%%. Got=%d Expected=%d", got, expected)
	}
}

func TestNewHashRing(t *testing.T) {
	nodes := []string{"a", "b", "c"}
	ring := NewHashRing(nodes, 120)

	if len(ring.sortedKeys) != 360 {
		t.Errorf("Number of nodes should equal server * nodesPerServer. Got=%d Expected=360", len(ring.sortedKeys))
	}
	if len(ring.sortedKeys) != len(ring.ring) {
		t.Error("sortedKeys should be the same size as ring")
	}

	validateDistribution(t, ring, nodes)
}

func TestNewHashRingWeighted(t *testing.T) {
	nodes := []string{"a", "b", "b", "c"}
	ring := NewHashRing(nodes, 120)

	if len(ring.sortedKeys) != 480 {
		t.Errorf("Number of nodes should equal server * nodesPerServer. Got=%d Expected=480", len(ring.sortedKeys))
	}
	if len(ring.sortedKeys) != len(ring.ring) {
		t.Error("sortedKeys should be the same size as ring")
	}

	validateDistribution(t, ring, nodes)
}

func BenchmarkGetNode(b *testing.B) {
	hashRing := NewHashRing([]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, 9000)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		hashRing.GetNode(keys[i%len(keys)])
	}
}

func BenchmarkGenKey(b *testing.B) {
	hashRing := NewHashRing([]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, 9000)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		hashRing.GenKey(keys[i%len(keys)])
	}
}
