package helpers

import (
	"fmt"
	"regexp"
)

// BuildpacksOutputRegex takes a BuildpackFields struct and returns a regex
// matching a line in the output of 'cf buildpacks' representing the given
// buildpack.
func BuildpacksOutputRegex(fields BuildpackFields) string {
	anyStringRegex := `\S+`
	optionalStringRegex := `\S*`
	anyBoolRegex := `(true|false)`
	anyIntRegex := `\d+`

	nameRegex := anyStringRegex
	if fields.Name != "" {
		nameRegex = regexp.QuoteMeta(fields.Name)
	}

	positionRegex := anyIntRegex
	if fields.Position != "" {
		positionRegex = regexp.QuoteMeta(fields.Position)
	}

	enabledRegex := anyBoolRegex
	if fields.Enabled != "" {
		enabledRegex = regexp.QuoteMeta(fields.Enabled)
	}

	lockedRegex := anyBoolRegex
	if fields.Locked != "" {
		lockedRegex = regexp.QuoteMeta(fields.Locked)
	}

	filenameRegex := anyStringRegex
	if fields.Filename != "" {
		filenameRegex = regexp.QuoteMeta(fields.Filename)
	}

	stackRegex := optionalStringRegex
	if fields.Stack != "" {
		stackRegex = regexp.QuoteMeta(fields.Stack)
	}

	return fmt.Sprintf(`%s\s+%s\s+%s\s+%s\s+%s\s+%s`,
		positionRegex,
		nameRegex,
		stackRegex,
		enabledRegex,
		lockedRegex,
		filenameRegex,
	)
}
