package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	socketio "github.com/googollee/go-socket.io"
)

func Setup(basePath string, server *socketio.Server) *gin.Engine {

	r := gin.Default()

	r.GET(basePath+"/check", func(c *gin.Context) {
		c.JSON(http.StatusAccepted, gin.H{"check": "good"})
	})

	//logger.RegisterLoggerRoutes(r, basePath, db)
	r.POST(basePath+"/update", func(c *gin.Context) {
		fmt.Println("Just hit the route")
		var payload UpdatePayload
		if err := c.BindJSON(&payload); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		fmt.Println("Past first json check")

		c.Writer.Header().Set("Content-Type", "text/event-stream")
		c.Writer.Header().Set("Cache-Control", "no-cache")
		c.Writer.Header().Set("Connection", "keep-alive")

		flusher, ok := c.Writer.(http.Flusher)
		if !ok {
			c.String(http.StatusInternalServerError, "Streaming not supported")
			return
		}

		fmt.Println("Past flusher")

		// Start the update and get the channel
		updates := UpdateApp(server)
		ctx := c.Request.Context() // Gin request context

		fmt.Println("attempting the loop")
		for {
			select {
			case <-ctx.Done():
				fmt.Println("Client closed connection")
				return
			case msg, ok := <-updates:
				if !ok {
					fmt.Fprintf(c.Writer, "Update process finished\n\n")
					flusher.Flush()
					return
				}
				fmt.Fprintf(c.Writer, "%s\n\n", msg)
				flusher.Flush()
			}
		}

	})

	r.Any(basePath+"/", func(c *gin.Context) { errorApiLoc(c) })

	return r
}

func errorApiLoc(c *gin.Context) {

	// log.Error("Api endpoint hit that dose not exist", "system", map[string]interface{}{
	// 	"endpoint":   c.Request.URL.Path,
	// 	"client_ip":  c.ClientIP(),
	// 	"user_agent": c.Request.UserAgent(),
	// })
	c.JSON(http.StatusBadRequest, gin.H{"message": "looks like you have encountered a route that dose not exist"})
}
