package cmd

import (
	"context"
	"fmt"
	"runtime"

	"code.icod.de/dalu/gomanager/ent"
	"code.icod.de/dalu/gomanager/ent/logentry"
	"code.icod.de/dalu/gomanager/ent/project"
	"entgo.io/ent/dialect/sql"
	"github.com/spf13/cobra"

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

var (
	showLogID = -1
)

// logsCmd represents the logs command
var logsCmd = &cobra.Command{
	Use:   "logs",
	Short: "Show logs of a 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()
		ms, e := client.Project.Query().Where(project.ID(showLogID)).
			QueryLogentries().
			Order(logentry.ByDate(sql.OrderDesc())).
			All(context.Background())
		if e != nil {
			return e
		}
		for _, m := range ms {
			fmt.Println(m.Date, m.Content)
		}
		return nil
	},
}

func init() {
	rootCmd.AddCommand(logsCmd)

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

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

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