package utils

import "strings"

type KeyType int

const (
	KeyEndpoints = "endpoints"
	KeyReplicas  = "replicas"

	KeyEndpointsType = iota
	KeyReplicasType
	KeyUnknownType
)

func (kt KeyType) String() string {
	switch kt {
	case KeyEndpointsType:
		return "KeyEndpoints"
	case KeyReplicasType:
		return "KeyReplicasType"
	default:
		return "KeyUnknownType"
	}
}

func ParseTokenFromKey(prefix, key string) (string, KeyType) {
	result := strings.Split(strings.TrimPrefix(key, prefix), "/")
	if len(result) == 2 {
		switch result[1] {
		case KeyEndpoints:
			return result[0], KeyEndpointsType
		case KeyReplicas:
			return result[0], KeyReplicasType
		}
	} else if len(result) == 3 {
		switch result[2] {
		case KeyEndpoints:
			return result[0] + "/" + result[1], KeyEndpointsType
		case KeyReplicas:
			return result[0] + "/" + result[1], KeyReplicasType
		}
	}
	return "", KeyUnknownType
}

func TrimToken(token string) string {
	idx := strings.IndexAny(token, ":/")
	if idx == -1 {
		return token
	}
	return token[:idx]
}

func TrimResourceGroup(token string) (rg string) {
	if parts := strings.Split(token, "/"); len(parts) > 1 {
		rg = parts[1]
	}
	return
}
