package cmd

import (
	"axolotl/models"
	"axolotl/service"
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var lTags, lRels []string
var lStatus, lPrio, lType, lNamespace, lAssignee, lMention string
var lDue bool
var lDueWithin int

var listCmd = &cobra.Command{
	Use: "list", Short: "List nodes",
	Run: func(cmd *cobra.Command, args []string) {
		svc, err := getNodeService()
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}

		var filter service.ListFilter
		filter.HasDueDate = lDue
		if lDueWithin >= 0 {
			n := lDueWithin
			filter.DueWithin = &n
		}

		// --tag is an alias for a label filter with no target.
		for _, tag := range lTags {
			filter.Rels = append(filter.Rels, service.RelInput{Type: models.RelType(tag), Target: ""})
		}

		// Shorthand flags expand to property filters or edge filters.
		if lStatus != "" {
			filter.Rels = append(filter.Rels, service.RelInput{Type: models.RelType("_status::" + lStatus), Target: ""})
		}
		if lPrio != "" {
			filter.Rels = append(filter.Rels, service.RelInput{Type: models.RelType("_prio::" + lPrio), Target: ""})
		}
		if lType != "" {
			filter.Rels = append(filter.Rels, service.RelInput{Type: models.RelType("_type::" + lType), Target: ""})
		}
		if lNamespace != "" {
			filter.Namespace = lNamespace
		}
		if lAssignee != "" {
			filter.Rels = append(filter.Rels, service.RelInput{Type: models.RelAssignee, Target: lAssignee})
		}
		if lMention != "" {
			filter.Rels = append(filter.Rels, service.RelInput{Type: models.RelMentions, Target: lMention})
		}

		for _, r := range lRels {
			ri, err := parseRelInput(r)
			if err != nil {
				fmt.Fprintf(os.Stderr, "failed to parse relation flag: %v", err)
				return
			}
			filter.Rels = append(filter.Rels, ri)
		}

		if nodes, err := svc.List(filter); err == nil {
			PrintNodes(cmd.OutOrStdout(), svc, nodes, jsonFlag)
		} else {
			fmt.Fprintf(os.Stderr, "err: %v\n", err)
		}
	},
}

func init() {
	rootCmd.AddCommand(listCmd)
	f := listCmd.Flags()
	f.StringArrayVar(&lTags, "tag", nil, "filter by label tag")
	f.StringArrayVar(&lRels, "rel", nil, "filter by relation (prefix::value or relname:target)")
	f.StringVar(&lStatus, "status", "", "filter by status")
	f.StringVar(&lPrio, "prio", "", "filter by priority")
	f.StringVar(&lType, "type", "", "filter by type")
	f.StringVar(&lNamespace, "namespace", "", "filter by namespace")
	f.StringVar(&lAssignee, "assignee", "", "filter by assignee")
	f.StringVar(&lMention, "mention", "", "filter by mention")
	f.BoolVar(&lDue, "due", false, "filter to nodes with a due date")
	f.IntVar(&lDueWithin, "due-within", -1, "filter to nodes due within N days (includes overdue)")
}
