package conf

import (
	"embed"
	"fmt"
	"io/fs"
	"log"
	"music-server/cmd/web"
	"music-server/pkg/api"
	"music-server/pkg/db"
	"music-server/pkg/helpers"
	"music-server/pkg/server"
	"net/http"
	"os"
	"strconv"

	"github.com/a-h/templ"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
)

func SetupDb() {

	/*err := server.ReadConf("conf.yaml")
	if err != nil {
		log.Fatal(err)
	}*/

	// 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 = "postgres"
	}
	if password == "" {
		password = "postgres"
	}
	if dbName == "" {
		dbName = "music_test_local"
	}

	db.Migrate_db(host, dbPort, username, password, dbName)

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

	var dir string
	if host != "localhost" {
		dir = "/sorted/"
	} else {
		dir = "/Users/sebastian/ResilioSync/Sorterat_test/"
	}

	server.Conf = &server.Config{
		Host:     host,
		Port:     dbPort,
		User:     username,
		Password: password,
		Dbname:   dbName,
		Path:     dir,
	}

}

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("/new", sync.SyncGamesNew)
		syncGroup.GET("/quick", sync.SyncGamesQuick)
		syncGroup.GET("/reset", sync.ResetGames)
	}

	music := api.NewMusic()
	musicGroup := router.Group("/music")
	{
		musicGroup.GET("", music.GetSong)
		musicGroup.GET("soundTest", music.GetSoundCheckSong)
		musicGroup.GET("reset", music.ResetMusic)
		musicGroup.GET("rand", music.GetRandomSong)
		musicGroup.GET("rand/low", music.GetRandomSongLowChance)
		musicGroup.GET("rand/classic", music.GetRandomSongClassic)
		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)
		musicGroup.GET("addPlayed", music.AddLatestPlayed)
	}

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

	staticFiles, _ := fs.Sub(web.Files, "assets")
	router.StaticFS("/assets", http.FS(staticFiles))
	router.GET("/search", func(c *gin.Context) {
		templ.Handler(web.HelloForm()).ServeHTTP(c.Writer, c.Request)
	})

	router.POST("/find", func(c *gin.Context) {
		web.FindGameWebHandler(c.Writer, c.Request)
	})

	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)
	err := router.Run(fmt.Sprintf(":%s", port))
	if err != nil {
		panic(err)
	}
}
