package commands

import (
	"fmt"
	"regexp"
	"strings"

	"git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/flag"
)

const (
	EntitiesPath    = "entities"
	ResourcesPath   = "resources"
	EnvironmentPath = "env"
)

var (
	upperCaseRegex = regexp.MustCompile(`(\s*([A-Z]))`)
	Commands       = map[string]func() error{
		"init":       initialize,
		"compile":    compile,
		"serve":      serve,
		"g.entity":   generateEntity,
		"g.resource": generateResource,
	}
	basePathFormats = map[bool]string{false: "./%s", true: "./%s/%s"}
)

func ExecuteWithFlags() (err error) {

	if err = flag.Initialize(); err != nil {
		return
	}

	command := flag.Command

	if callback, exist := Commands[command]; exist {
		err = callback()
		return
	}

	err = fmt.Errorf("The command '%s' is not valid", command)
	return
}

func basePath() string {
	return basePathWithComplement("")
}

func basePathWithComplement(complement string) string {
	return fmt.Sprintf(
		basePathFormats[complement != ""],
		project.ID,
		complement,
	)
}

func normalizePath(path string) string {
	path = upperCaseRegex.ReplaceAllStringFunc(path, func(m string) string {
		return fmt.Sprintf("-%s", strings.ToLower(strings.Trim(m, " ")))
	})
	path = strings.ReplaceAll(path, " ", "-")
	path = strings.Trim(path, "-")
	return path
}
