package commands

import (
	"os"

	"git.ctrlz.es/mgdelacroix/craban/server"

	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
)

func GameCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "game",
		Short: "Game related commands",
	}

	cmd.AddCommand(
		CreateGameCmd(),
		ListGameCmd(),
	)

	return cmd
}

func CreateGameCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "create",
		Short: "Create a new game",
		Args:  cobra.NoArgs,
		Run:   createGameCmdF,
	}

	cmd.Flags().StringP("owner", "o", "", "the username of the owner")
	cmd.MarkFlagRequired("owner")
	cmd.Flags().StringP("name", "n", "", "the name of the game")
	cmd.MarkFlagRequired("name")

	return cmd
}

func ListGameCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "list",
		Short: "List all games",
		Args:  cobra.NoArgs,
		Run:   listGameCmdF,
	}
}

func createGameCmdF(cmd *cobra.Command, _ []string) {
	name, _ := cmd.Flags().GetString("name")
	owner, _ := cmd.Flags().GetString("owner")

	config, _ := cmd.Flags().GetString("config")
	srv, err := server.NewServerWithConfigPath(config)
	if err != nil {
		log.Error().Err(err).Msg("cannot create server")
		os.Exit(1)
	}
	defer srv.Store.Close()

	user, err := srv.App.GetUserByUsername(owner)
	if err != nil {
		log.Error().Err(err).Msg("owner couldn't be fetch")
		os.Exit(1)
	}

	game, err := srv.App.CreateGame(name, user.ID)
	if err != nil {
		log.Error().Err(err).Msg("user couldn't be created")
		os.Exit(1)
	}

	log.Info().Str("name", game.Name).Msg("game successfully created")
}

func listGameCmdF(cmd *cobra.Command, _ []string) {
	config, _ := cmd.Flags().GetString("config")
	srv, err := server.NewServerWithConfigPath(config)
	if err != nil {
		log.Error().Err(err).Msg("cannot create server")
		os.Exit(1)
	}
	defer srv.Store.Close()

	games, err := srv.App.ListGames()
	if err != nil {
		log.Error().Err(err).Msg("cannot get game list")
		os.Exit(1)
	}

	for _, game := range games {
		log.Info().
			Str("name", game.Name).
			Int("userID", game.UserID).
			Msg("")
	}
}
