package rediczar

import "fmt"

const delimiter = ":"

// prefixKey joins the key and prefix with `delimiter`. If prefix is an empty string, then `key`
// is returned
func prefixKey(key string, prefix string) string {
	if prefix == "" {
		return key
	}
	return prefix + delimiter + key
}

// prefixKeys calls prefixKey for each element in `keys`
func prefixKeys(keys []string, prefix string) []string {
	if prefix == "" || len(keys) == 0 {
		return keys
	}

	out := make([]string, len(keys))

	for i := range keys {
		out[i] = prefixKey(keys[i], prefix)
	}

	return out
}

// prefixPairs processes a slice of interface{}, where every even-index element
// is a string, and every odd-index element is an arbitrary value. It skips every other element to
// prefix only the keys.
func prefixPairs(pairs []interface{}, prefix string) ([]interface{}, error) {
	if prefix == "" || len(pairs) == 0 {
		return pairs, nil
	}

	out := make([]interface{}, len(pairs))

	for i, v := range pairs {
		if i%2 == 0 {
			s, ok := v.(string)
			if !ok {
				return nil, fmt.Errorf("prefixPairs: cannot prefix non-string key %v", v)
			}
			out[i] = prefixKey(s, prefix)
		} else {
			out[i] = v
		}
	}

	return out, nil
}
