package recipe

import (
	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/urfave/cli"
)

var recipeFetchCommand = cli.Command{
	Name:        "fetch",
	Usage:       "Fetch recipe(s)",
	Aliases:     []string{"f"},
	ArgsUsage:   "[<recipe>]",
	Description: "Retrieves all recipes if no <recipe> argument is passed",
	Flags: []cli.Flag{
		internal.DebugFlag,
		internal.NoInputFlag,
		internal.OfflineFlag,
	},
	Before:       internal.SubCommandBefore,
	BashComplete: autocomplete.RecipeNameComplete,
	Action: func(c *cli.Context) error {
		recipeName := c.Args().First()
		r := recipe.Get(recipeName)
		if recipeName != "" {
			internal.ValidateRecipe(c)
			if err := r.Ensure(false, false); err != nil {
				log.Fatal(err)
			}
			return nil
		}

		catalogue, err := recipe.ReadRecipeCatalogue(internal.Offline)
		if err != nil {
			log.Fatal(err)
		}

		catlBar := formatter.CreateProgressbar(len(catalogue), "fetching latest recipes...")
		for recipeName := range catalogue {
			r := recipe.Get(recipeName)
			if err := r.Ensure(false, false); err != nil {
				log.Error(err)
			}
			catlBar.Add(1)
		}

		return nil
	},
}
