package autocomplete

import (
	"fmt"

	"coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/urfave/cli"
)

// AppNameComplete copletes app names.
func AppNameComplete(c *cli.Context) {
	appNames, err := app.GetAppNames()
	if err != nil {
		log.Warn(err)
	}

	if c.NArg() > 0 {
		return
	}

	for _, a := range appNames {
		fmt.Println(a)
	}
}

func ServiceNameComplete(appName string) {
	serviceNames, err := app.GetAppServiceNames(appName)
	if err != nil {
		return
	}
	for _, s := range serviceNames {
		fmt.Println(s)
	}
}

// RecipeNameComplete completes recipe names.
func RecipeNameComplete(c *cli.Context) {
	catl, err := recipe.ReadRecipeCatalogue(false)
	if err != nil {
		log.Warn(err)
	}

	if c.NArg() > 0 {
		return
	}

	for name := range catl {
		fmt.Println(name)
	}
}

// RecipeVersionComplete completes versions for the recipe.
func RecipeVersionComplete(recipeName string) {
	catl, err := recipe.ReadRecipeCatalogue(false)
	if err != nil {
		log.Warn(err)
	}

	for _, v := range catl[recipeName].Versions {
		for v2 := range v {
			fmt.Println(v2)
		}
	}
}

// ServerNameComplete completes server names.
func ServerNameComplete(c *cli.Context) {
	files, err := app.LoadAppFiles("")
	if err != nil {
		log.Fatal(err)
	}

	if c.NArg() > 0 {
		return
	}

	for _, appFile := range files {
		fmt.Println(appFile.Server)
	}
}

// SubcommandComplete completes sub-commands.
func SubcommandComplete(c *cli.Context) {
	if c.NArg() > 0 {
		return
	}

	subcmds := []string{
		"app",
		"autocomplete",
		"catalogue",
		"recipe",
		"server",
		"upgrade",
	}

	for _, cmd := range subcmds {
		fmt.Println(cmd)
	}
}
