package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"gitlab.com/pcanilho/go-jira"
	"gitlab.com/pcanilho/go-jira-cli/cmd/errors"
	"os"
)

var searchCmd = &cobra.Command{
	Use:   "search",
	Short: "Searches for a Jira ticket based on the supplied JQL query",
	Example: fmt.Sprintf(`
# Search for issues created in the last 4 weeks and sort by created date
%s search 'created >= -4w ORDER BY created DESC'`, name),
	RunE: func(cmd *cobra.Command, args []string) error {
		if len(args) == 0 {
			return fmt.Errorf("please specify a JQL query")
		}
		issues, err := jiraController.SearchIssues(args[0], composeSearchOptions(), maxOccurrences)
		if err != nil {
			return errors.NewCliError(err)
		}
		if len(issues) == 0 {
			os.Exit(1)
		}

		// Set output
		outputIssueList = issues
		return nil
	},
}

func init() {
	searchCmd.PersistentFlags().IntVarP(&limitResults, "limit", "l", 0, "limit the amount of issues to be retrieved (defaults to all)")
	searchCmd.PersistentFlags().IntVarP(&maxOccurrences, "max-output", "o", 0, "raises an error if the total output amount exceeds the provided value (defaults to all)")

	// Add commands
	for operator, cs := range operatorCmdMap {
		for _, c := range cs {
			addCommonFlags(c)
			addCommonFunc(c, operator)
			searchCmd.AddCommand(c)
		}
	}
}

func composeSearchOptions() *jira.SearchOptions {
	return &jira.SearchOptions{
		MaxResults: limitResults,
	}
}