package cmd

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

var dForce bool
var delCmd = &cobra.Command{
	Use: "del <id>", Short: "Delete a node", Args: cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		svc, err := getNodeService()
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}

		n, err := svc.GetByID(args[0])
		if err != nil {
			fmt.Fprintf(os.Stderr, "node not found: %s\n", args[0])
			os.Exit(1)
		}

		if !dForce {
			fmt.Printf("Delete %s '%s'? [y/N]: ", n.GetProperty("type"), n.Title)
			r, _ := bufio.NewReader(os.Stdin).ReadString('\n')
			if r = strings.TrimSpace(strings.ToLower(r)); r != "y" && r != "yes" {
				fmt.Println("Cancelled.")
				return
			}
		}

		if err := svc.Delete(args[0]); err != nil {
			fmt.Fprintf(os.Stderr, "failed to delete: %v", err)
		} else {
			PrintAction(cmd.OutOrStdout(), "Deleted", args[0], true)
		}
	},
}

func init() {
	rootCmd.AddCommand(delCmd)
	delCmd.Flags().BoolVarP(&dForce, "force", "f", false, "")
}
