/*
Copyright © 2024 Brian Buller <brian@bullercodeworks.com>
*/
package cmd

import (
	"errors"
	"fmt"
	"strings"

	"git.bullercodeworks.com/brian/keepass-cli/models"
	"git.bullercodeworks.com/brian/keepass-cli/util"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	kp "github.com/tobischo/gokeepasslib"
)

// getCmd represents the get command
var getCmd = &cobra.Command{
	Use:   "get",
	Short: "Get the password for an entry",
	RunE:  runGetCmd,
}

func init() {
	rootCmd.AddCommand(getCmd)
}

func runGetCmd(cmd *cobra.Command, args []string) error {
	var path []string
	for i := range args {
		path = append(path, strings.Split(args[i], "/")...)
	}
	var db *models.KeePassDB
	pass, err := util.PromptUserForPassword("Master Password")
	if err != nil {
		return err
	}
	db, err = models.NewKeePassDB(viper.GetString("database"), pass)
	if err != nil {
		return err
	}
	var entry *kp.Entry
	for entry == nil {
		var entryErr error
		list := db.GetGroupsAndEntriesFromRoot(path)
		if len(list) == 0 {
			return errors.New("Invalid Path")
		} else if len(list) > 1 {
			for i := range list {
				fmt.Printf("%d. %s\n", i+1, list[i])
			}
			idx := util.PromptUserInt("Choice:")
			path = list[idx-1]
		} else {
			// Only one... Could be a single group nested, or it's an entry
			entry, entryErr = db.FindEntryFromRoot(path)
			if entryErr == nil {
				fmt.Println(entry.GetPassword())
				return util.WriteToClipboard(entry.GetPassword())
			}
			// It's a group
			path = list[0]
		}
	}

	return nil
}
