package signature

import (
	"strings"
)

// kvItem is used to sort a map's key value pairs by key then value
type kvItem struct {
	Key   string
	Value string
}

type kvItems []kvItem

func (t kvItems) Len() (l int) {
	l = len(t)
	return
}

func (t kvItems) Less(i, j int) (less bool) {
	cmp := strings.Compare(t[i].Key, t[j].Key)
	if cmp != 0 {
		less = cmp < 0
		return
	}
	cmp = strings.Compare(t[i].Value, t[j].Value)
	less = cmp < 0
	return
}

func (t kvItems) Swap(i, j int) {
	t[i], t[j] = t[j], t[i]
}

func newKVItems(kv map[string][]string) (items kvItems) {
	var valueCount int
	for _, v := range kv {
		valueCount += len(v)
	}
	items = make(kvItems, 0, valueCount)

	for key, hValues := range kv {
		for _, hValue := range hValues {
			items = append(items, kvItem{Key: key, Value: hValue})
		}
	}
	return
}
