package rest_websocket

import (
	"context"
	"log"
	"net/http"

	"git.ali33.ru/fcg-xvii/go-tools/json"
	"git.ali33.ru/fcg-xvii/rest"
	"github.com/gorilla/websocket"
)

type appConfig struct {
	app            IApplication
	core           any
	ctx            context.Context
	tokenGenerator func(json.Map, int64) (string, error)
}

func New(app IApplication, core any) *Rest {
	return &Rest{
		upgrader: &websocket.Upgrader{
			ReadBufferSize:  1024,
			WriteBufferSize: 1024,
		},
		appConf: &appConfig{
			app:  app,
			core: core,
		},
	}
}

type Rest struct {
	upgrader *websocket.Upgrader
	appConf  *appConfig
	server   rest.IServer
}

// Listen start server in other goroutine
func (s *Rest) Prepare(server rest.IServer, httpPrefix string) {
	s.appConf.ctx = server.Context()
	s.appConf.tokenGenerator = server.TokenGenerate
	server.HandleFunc(httpPrefix, s.handle)
	s.server = server
}

func (s *Rest) handle(w http.ResponseWriter, r *http.Request) {
	// Преобразование HTTP соединения в WebSocket соединение
	ws, err := s.upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
	}
	socket := newWebSocket(ws, s.appConf)
	s.appConf.app.Incoming() <- socket
}
