package websocket

import (
	"net/http"
	"primesys_command_producer/src/logger"
)

func SocketServer(socketAddr string) error {

	logger.Info("socket addr %s", socketAddr)

	hub := socketHub
	go hub.run()

	http.HandleFunc("/commandws", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			logger.Error("Wrong method used")
			http.Error(w, "Illegal Method requested", http.StatusBadRequest)
			return
		}

		userId := r.URL.Query().Get("userId")
		logger.Info("User Id is required")
		if userId == "" {
			http.Error(w, "divisionId is required", http.StatusBadRequest)
			return
		}

		serveWs(userId, hub, w, r)
	})

	logger.Info("Socket server started on %s......", socketAddr)
	return http.ListenAndServe(socketAddr, nil)
}
