package cmd

import (
	"context"
	"errors"
	"fmt"
	"runtime"

	"code.icod.de/dalu/gomanager/ent"
	"github.com/spf13/cobra"

	_ "github.com/mattn/go-sqlite3"
)

var (
	removeID = -1
)

// removeCmd represents the remove command
var removeCmd = &cobra.Command{
	Use:   "remove",
	Short: "Remove a job with an ID",
	Long: `Remove a job with an ID

Use gomanager list to find the project's (or job's) ID.
Example:
sudo ./gomanager list
+---------------------------------------------------------------------------------------------------------------------+
| Watched Projects                                                                                                    |
+----+---------------------------------------------------+-------------+---------------------+-------+-------+--------+
| ID | ROOT PATH                                         | BINARY      | SERVICE NAME        | USER  | GROUP | TARGET |
+----+---------------------------------------------------+-------------+---------------------+-------+-------+--------+
|  1 | /home/darko/go/src/code.icod.de/dalu/simpleforum/ | simpleforum | simpleforum.service | nginx | nginx |        |
|  2 | /home/darko/go/src/code.icod.de/dalu/affx/        | affx        | affx.service        | nginx | nginx |        |
+----+---------------------------------------------------+-------------+---------------------+-------+-------+--------+

Then use
gomanager remove --id=1
to remove the simpleforum project

'
`,
	RunE: func(cmd *cobra.Command, args []string) error {
		runtime.GOMAXPROCS(1)
		client, err := ent.Open("sqlite3", fmt.Sprintf("file:%s?mode=rwc&cache=private&_fk=1", sqliteFilename))
		if err != nil {
			return fmt.Errorf("failed opening connection to sqlite: %v", err)
		}
		defer client.Close()
		if removeID == -1 {
			return errors.New("the ID is not set. Use --id=<number> to remove a job with a <number> ID")
		}
		return client.Project.DeleteOneID(removeID).Exec(context.Background())
	},
}

func init() {
	rootCmd.AddCommand(removeCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// removeCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// removeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	removeCmd.Flags().IntVar(&removeID, "id", -1, "1")
}
