package diff

import "strings"

/*
normalizeTemplatedPath converts a path to its normalized form, without parameter names

For example:
/person/{personName} -> /person/{}

Return values:
1. The normalized path
2. Number of params
3. List of param names

This implementation is based on Paths.normalizeTemplatedPath in openapi3
*/
func normalizeTemplatedPath(path string) (string, uint, []string) {
	if strings.IndexByte(path, '{') < 0 {
		return path, 0, nil
	}

	var buffTpl strings.Builder
	buffTpl.Grow(len(path))

	var (
		cc         rune
		count      uint
		isVariable bool
		vars       = []string{}
		buffVar    strings.Builder
	)
	for i, c := range path {
		if isVariable {
			if c == '}' {
				// End path variable
				isVariable = false

				vars = append(vars, buffVar.String())
				buffVar = strings.Builder{}

				// First append possible '*' before this character
				// The character '}' will be appended
				if i > 0 && cc == '*' {
					buffTpl.WriteRune(cc)
				}
			} else {
				buffVar.WriteRune(c)
				continue
			}

		} else if c == '{' {
			// Begin path variable
			isVariable = true

			// The character '{' will be appended
			count++
		}

		// Append the character
		buffTpl.WriteRune(c)
		cc = c
	}
	return buffTpl.String(), count, vars
}
