package recipe

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

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

var pattern string
var patternFlag = &cli.StringFlag{
	Name:        "pattern, p",
	Value:       "",
	Usage:       "Simple string to filter recipes",
	Destination: &pattern,
}

var recipeListCommand = cli.Command{
	Name:    "list",
	Usage:   "List available recipes",
	Aliases: []string{"ls"},
	Flags: []cli.Flag{
		internal.DebugFlag,
		internal.MachineReadableFlag,
		patternFlag,
		internal.OfflineFlag,
	},
	Before: internal.SubCommandBefore,
	Action: func(c *cli.Context) error {
		catl, err := recipe.ReadRecipeCatalogue(internal.Offline)
		if err != nil {
			log.Fatal(err.Error())
		}

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

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

		headers := []string{
			"name",
			"category",
			"status",
			"healthcheck",
			"backups",
			"email",
			"tests",
			"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("unable to render to JSON: %s", err)
				}
				fmt.Println(out)
				return nil
			}

			fmt.Println(table)
			log.Infof("total recipes: %v", len(rows))
		}

		return nil
	},
}
