package shared

import (
	"strings"
	"unicode"
)

// NormalizedTokens returns identity-normalized alphanumeric tokens from a
// D&D value.
func NormalizedTokens(value string) []string {
	value = ComparisonKey(value)
	if value == "" {
		return nil
	}
	return strings.FieldsFunc(value, func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsDigit(r)
	})
}

// ContainsTokenSequence reports whether value contains the complete normalized
// query token sequence as consecutive tokens.
func ContainsTokenSequence(value string, query string) bool {
	valueTokens := NormalizedTokens(value)
	queryTokens := NormalizedTokens(query)
	if len(queryTokens) == 0 || len(queryTokens) > len(valueTokens) {
		return false
	}
	for start := 0; start <= len(valueTokens)-len(queryTokens); start++ {
		matches := true
		for offset, token := range queryTokens {
			if valueTokens[start+offset] != token {
				matches = false
				break
			}
		}
		if matches {
			return true
		}
	}
	return false
}
