package server

import (
	"encoding/json"
	"fmt"

	"github.com/gorilla/websocket"
	"github.com/labstack/echo/v4"
)

var upgrader = websocket.Upgrader{}

type WebsocketServer struct {
	router *echo.Echo
}

func (s *WebsocketServer) Initialize(authenticator *Authenticator) {
	//s.router.Use(authenticator.Authenticate("/ws/terminal", []string{}))
	s.router.GET("/ws", s.handle)
}

func (s *WebsocketServer) handle(context echo.Context) error {
	//authContext := context.(AuthContext)
	ws, err := upgrader.Upgrade(context.Response(), context.Request(), nil)
	if err != nil {
		return err
	}
	defer ws.Close()

	for {
		messageType, messageBytes, err := ws.ReadMessage()
		if err != nil {
			return err
		}
		if messageType == websocket.TextMessage {
			var messageObject map[string]any
			json.Unmarshal(messageBytes, &messageObject)
			fmt.Println(messageObject)
		}
	}
}

func (s *WebsocketServer) SetRouter(router *echo.Echo) {
	s.router = router
}
