package common

import (
	"errors"
	"fmt"
	"strings"
)

func GetRequestPath(param *AccessParam) string {
	path, _ := param.Metadata[METADATA_PATH].(string)
	return path
}

func GetRequestMethod(param *AccessParam) string {
	method, _ := param.Metadata[METADATA_METHOD].(string)
	return method
}

func ParsePathPattern(pathPattern string) (path, method string, err error) {
	split := strings.Split(pathPattern, PATH_METHOD_SEPERATOR)
	if len(split) == 1 {
		path = split[0]
	} else if len(split) == 2 {
		method = split[0]
		path = split[1]
	} else {
		return "", "", errors.New(fmt.Sprintf("invalid path_pattern: %s", pathPattern))
	}
	return path, method, nil
}

func ParseCascadeResourceValue(resourceUri string, resourceTypes []string) map[string]string {
	resourceSlice := strings.Split(resourceUri, RESOURCE_VALUE_SEPARATOR)
	length := len(resourceSlice)

	var resourceTypeMap = map[string]struct{}{}
	for _, resourceType := range resourceTypes {
		resourceTypeMap[resourceType] = struct{}{}
	}

	var resourceType2ValueMap = map[string]string{}
	for i := 0; i < length; i++ {
		str := resourceSlice[i]
		_, ok := resourceTypeMap[str]
		if ok && i+1 < length {
			resourceType2ValueMap[str] = resourceSlice[i+1]
		}
	}
	return resourceType2ValueMap
}

func GetCascadeResourceValue(resourceUri string, resourceType string) (string, bool) {
	resourceValueMap := ParseCascadeResourceValue(resourceUri, []string{resourceType})
	value, found := resourceValueMap[resourceType]
	return value, found
}
