package cmd

import (
	"fmt"
	"log"
	"os"

	"gitlab.thpeetz.de/kontor/kontor-go/pkg/properties"
	"gitlab.thpeetz.de/kontor/kontor-go/pkg/setup"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var (
	// Verbose defines the parameter verbose.
	Verbose bool
	// Version defines the version of the web application.
	Version string
	// Debug defines the debug parameter.
	Debug bool
	// Port defines the parameter port.
	Port int
	// TemplatesDir defines the root directory of template files.
	TemplatesDir string
	router       *gin.Engine
)

var rootCmd = &cobra.Command{
	Use:   "kontor",
	Short: "kontor",
	Long:  `kontor`,
	Run: func(cmd *cobra.Command, args []string) {
		// Set Gin to production mode
		if Debug {
			gin.SetMode(gin.DebugMode)
		} else {
			gin.SetMode(gin.ReleaseMode)
		}
		log.SetOutput(gin.DefaultWriter)

		// Set the router as the default one provided by Gin
		router = gin.Default()

		// Process the templates at the start so that they don't have to be loaded
		// from the disk again. This makes serving HTML pages very fast.
		templatesDir := fmt.Sprintf("%s/**/*", TemplatesDir)
		log.Printf("load template files from %v", templatesDir)
		router.LoadHTMLGlob(templatesDir)

		// Use Middleware logger
		router.Use(gin.Logger())

		// Initialize the routes
		setup.InitializeRoutes(router)

		// Clean up SetSessionStatus
		setup.CleanupSessions()

		// Check if at least one user configured
		setup.CheckUserList()

		// Check if data for TradeYourSportsCards is available
		setup.CheckTradeYourSportsCardsData()

		//properties.SetVersion(Version)

		// Start serving the application
		server := fmt.Sprintf("127.0.0.1:%d", Port)
		router.Run(server)
	},
}

// Execute parses the commandline and calls Execute on rootCmd.
func Execute(version string) {
	rootCmd.Version = version
	properties.SetVersion(version)
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
	rootCmd.PersistentFlags().BoolVarP(&Debug, "debug", "d", false, "debug modus")
	rootCmd.PersistentFlags().IntVarP(&Port, "port", "p", 8500, "port number")
	rootCmd.PersistentFlags().StringVarP(&TemplatesDir, "templates", "t", "templates", "path for template files")
}
