package struct_utils

import "strings"

// KeyValuePair defines a key/value pair derived from form data
type KeyValuePair struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

// FormToKeyValuePairs returns a string-based map of strings as derived from posted form keys and values.
// e.g. oauth_consumer_key=mlhgs&oauth_consumer_secret=x240ar&oauth_verifier=b0qjbx&store_base_url=http%3A%2F%2Flocalhost.com%2Fstore
func FormToKeyValuePairs(body string) []KeyValuePair {
	out := []KeyValuePair{}
	parts := strings.Split(body, "&")
	for _, p := range parts {
		split := strings.Split(p, "=")

		var key string
		if len(split) > 0 {
			key = split[0]
		}

		var value string
		if len(split) > 1 {
			key = split[1]
		}

		kv := KeyValuePair{
			Key:   key,
			Value: value,
		}
		out = append(out, kv)
	}

	return out
}

// GetValue returns the value for the given key from a KeyValuePair slice.
func GetValue(key string, kv []KeyValuePair) string {
	for _, v := range kv {
		if v.Key == key {
			return v.Value
		}
	}

	return ""
}