package httproute

import (
	"fmt"
	"net/url"
	"strings"
)

// capturePathParams captures request parameters that have been bound to
// segments of the URI path.
func (t *Template) capturePathParams(path string) (url.Values, error) {
	var parts []string
	t.traverse(path, func(seg string) {
		parts = append(parts, seg)
	})

	// This is initialized once we've had an opportunity to detect a
	// suspiciously short template. Implicitly handing the weird error case
	// helps with test coverage :)
	var vals url.Values

	for _, seg := range t.segments {
		if vals == nil {
			vals = make(url.Values)
		}
		length := 1
		if seg.variable != nil {
			length = len(seg.variable.segments)
		}
		if length > len(parts) {
			// The method has been called with a path that doesn't match the
			// template. Make a controlled panic so we can fix whatever
			// invariant-breaking bug we've encountered.
			panic(fmt.Errorf("invariant broken: path does not match template (%q).capturePathParams(%q)", t, path))
		}
		capture := parts[:length]
		parts = parts[length:]

		for i := range capture {
			v, err := url.PathUnescape(capture[i])
			if err != nil {
				return nil, err
			}
			capture[i] = v
		}

		if seg.variable != nil {
			vals.Add(seg.variable.fieldPath.String(), strings.Join(capture, "/"))
		}
	}

	return vals, nil
}
