package conf

import (
	"embed"
	"fmt"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	"log"
	"music-server/pkg/api"
	"music-server/pkg/db"
	"music-server/pkg/helpers"
	"os"
	"strconv"
)

func SetupDb() {
	// Get the value of an Environment Variable
	host := os.Getenv("DB_HOST")
	dbPort, dbPortErr := strconv.Atoi(os.Getenv("DB_PORT"))
	if dbPortErr != nil {
		dbPort = 0
	}
	username := os.Getenv("DB_USERNAME")
	password := os.Getenv("DB_PASSWORD")
	dbName := os.Getenv("DB_NAME")

	fmt.Printf("host: %s, dbPort: %v, username: %s, password: %s, dbName: %s\n",
		host, dbPort, username, password, dbName)

	if host == "" {
		host = "localhost"
	}
	if dbPort == 0 {
		dbPort = 5432
	}
	if username == "" {
		username = "sebastian"
	}
	if password == "" {
		password = "950100"
	}
	if dbName == "" {
		dbName = "music_dev_local"
	}

	db.InitDB(host, dbPort, username, password, dbName)
}

func CloseDb() {
	defer db.CloseDb()
}

func SetupRestServer(swagger embed.FS) {

	router := gin.Default()
	router.Use(helpers.SetCorsAndNoCacheHeaders())

	sync := api.NewSync()
	syncGroup := router.Group("/sync")
	{
		syncGroup.GET("", sync.SyncGames)
		syncGroup.GET("/reset", sync.ResetGames)
	}

	music := api.NewMusic()
	musicGroup := router.Group("/music")
	{
		musicGroup.GET("", music.GetSong)
		musicGroup.GET("first", music.GetMusicFirst)
		musicGroup.GET("reset", music.ResetMusic)
		musicGroup.GET("rand", music.GetRandomSong)
		musicGroup.GET("rand/low", music.GetRandomSongLowChance)
		musicGroup.GET("info", music.GetSongInfo)
		musicGroup.GET("list", music.GetPlayedSongs)
		musicGroup.GET("next", music.GetNextSong)
		musicGroup.GET("previous", music.GetPreviousSong)
		musicGroup.GET("all", music.GetAllGamesRandom)
		musicGroup.GET("all/order", music.GetAllGames)
		musicGroup.GET("all/random", music.GetAllGamesRandom)
		musicGroup.PUT("played", music.PutPlayed)
		musicGroup.GET("addQue", music.AddLatestToQue)
	}

	index := api.NewIndex()
	router.GET("/version", index.GetVersion)
	router.GET("/test", index.GetDBTest)
	router.StaticFS("/swagger", helpers.EmbedFolder(swagger, "swagger", false))
	router.Use(static.Serve("/", static.LocalFile("frontend/dist", true)))

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("Defaulting to port %s", port)
	}
	log.Printf("Open http://localhost:%s in the browser", port)
	router.Run(fmt.Sprintf(":%s", port))
}
