package serra

import (
	"strings"

	"github.com/spf13/cobra"
	"go.mongodb.org/mongo-driver/bson"
)

func init() {
	deckCmd.Flags().Int64VarP(&count, "count", "c", 1, "Amount of cards to add")
	deckCmd.Flags().BoolVarP(&foil, "foil", "f", false, "Add foil variant of card")
	rootCmd.AddCommand(deckCmd)
}

var deckCmd = &cobra.Command{
	Aliases:       []string{"d"},
	Use:           "deck",
	Short:         "Mark a card as in a deck",
	Long:          "Mark a card as in a deck",
	SilenceErrors: true,
	RunE: func(cmd *cobra.Command, cards []string) error {
		deckCards(cards, count)
		return nil
	},
}

func deckCards(cards []string, count int64) error {
	client := storageConnect()
	coll := &Collection{client.Database("serra").Collection("cards")}
	l := Logger()
	defer storageDisconnect(client)

	// Loop over different cards
	for _, card := range cards {
		// Extract collector number and set name from card input & trim any leading 0 from collector number

		if !strings.Contains(card, "/") {
			l.Errorf("Invalid card format %s. Needs to be set/collector number i.e. \"usg/13\"", card)
			continue
		}

		setName := strings.ToLower(strings.Split(card, "/")[0])
		collectorNumber := strings.TrimLeft(strings.Split(card, "/")[1], "0")

		if collectorNumber == "" {
			l.Errorf("Invalid card format %s. Needs to be set/collector number i.e. \"usg/13\"", card)
			continue
		}

		// Check if card is already in collection
		co, err := coll.storageFind(bson.D{{"set", setName}, {"collectornumber", collectorNumber}}, bson.D{}, 0, 0)
		if err != nil {
			l.Error(err)
			continue
		}

		if len(co) >= 1 {
			modifyCardDeckCount(coll, &co[0], count, foil)
		} else {
			l.Errorf("Card not in collection: %s", card)
			continue
		}
	}
	storageDisconnect(client)
	return nil
}
