package recipe

import (
	"fmt"
	"sort"
	"strconv"
	"strings"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/i18n"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/spf13/cobra"
)

// translators: `abra recipe list` aliases. use a comma separated list of
// aliases with no spaces in between
var recipeListAliases = i18n.G("ls")

var RecipeListCommand = &cobra.Command{
	// translators: `recipe list` command
	Use: i18n.G("list"),
	// translators: Short description for `recipe list` command
	Short:   i18n.G("List recipes"),
	Aliases: strings.Split(recipeListAliases, ","),
	Args:    cobra.NoArgs,
	Run: func(cmd *cobra.Command, args []string) {
		catl, err := recipe.ReadRecipeCatalogue(internal.Offline)
		if err != nil {
			log.Fatal(err)
		}

		recipes := catl.Flatten()
		sort.Sort(recipe.ByRecipeName(recipes))

		table, err := formatter.CreateTable()
		if err != nil {
			log.Fatal(err)
		}

		headers := []string{
			i18n.G("name"),
			i18n.G("category"),
			i18n.G("status"),
			i18n.G("healthcheck"),
			i18n.G("backups"),
			i18n.G("email"),
			i18n.G("tests"),
			i18n.G("SSO"),
		}

		table.Headers(headers...)

		var rows [][]string
		for _, recipe := range recipes {
			row := []string{
				recipe.Name,
				recipe.Category,
				strconv.Itoa(recipe.Features.Status),
				recipe.Features.Healthcheck,
				recipe.Features.Backups,
				recipe.Features.Email,
				recipe.Features.Tests,
				recipe.Features.SSO,
			}

			if pattern != "" {
				if strings.Contains(recipe.Name, pattern) {
					table.Row(row...)
					rows = append(rows, row)
				}
			} else {
				table.Row(row...)
				rows = append(rows, row)
			}
		}

		if len(rows) > 0 {
			if internal.MachineReadable {
				out, err := formatter.ToJSON(headers, rows)
				if err != nil {
					log.Fatal(i18n.G("unable to render to JSON: %s", err))
				}
				fmt.Println(out)
				return
			}

			if err := formatter.PrintTable(table); err != nil {
				log.Fatal(err)
			}
		}
	},
}

var (
	pattern string
)

func init() {
	RecipeListCommand.Flags().BoolVarP(
		&internal.MachineReadable,
		i18n.G("machine"),
		i18n.G("m"),
		false,
		i18n.G("print machine-readable output"),
	)

	RecipeListCommand.Flags().StringVarP(
		&pattern,
		i18n.G("pattern"),
		i18n.G("p"),
		"",
		i18n.G("filter by recipe"),
	)
}
