package cmd

import (
	"code.icod.de/dalu/gomanager/runner"
	"fmt"
	"runtime"
	"time"

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

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

// startCmd represents the start command
var startCmd = &cobra.Command{
	Use:   "start",
	Short: "starts the autonomous watcher mode, which checks projects every 24h",
	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()
		r := runner.NewRunner(client)
		t := time.NewTicker(time.Hour * 24)
		for {
			select {
			case <-t.C:
				if e := r.Run(); e != nil {
					return e
				}
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(startCmd)

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

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

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