package util

import (
	"math/rand"
	"regexp"

	"k8s.io/utils/ptr"
)

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

// Truncate truncates a string to a maximum length.
func Truncate(s string, maxLen int) string {
	if len(s) > maxLen {
		return s[:maxLen]
	}
	return s
}

func RandStringRunes(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

func IsAWSIAMARN(str string) bool {
	m, _ := regexp.MatchString(`^arn:aws:iam::\d+:\S*`, str)
	return m
}

func IsGCPServiceAccount(str string) bool {
	// GCP Service Account format: name@project-id.iam.gserviceaccount.com
	m, _ := regexp.MatchString(`^\S+@\S+\.iam\.gserviceaccount\.com$`, str)
	return m
}

// ToSlicePointer converts a slice of values to a slice of pointers to those values.
// It takes the originalSlice as input and returns a new slice containing pointers to each element in the originalSlice.
func ToSlicePointer[V any](originalSlice []V) []*V {
	sli := make([]*V, 0, len(originalSlice))
	for _, v := range originalSlice {
		// ptr.To returns a pointer to the value passed in
		// we should use ptr.To instead of &v to avoid the same pointer address
		sli = append(sli, ptr.To(v))
	}
	return sli
}
