package handler import ( "log" "mchess_server/api" "mchess_server/chess" lobbies "mchess_server/lobby_registry" "mchess_server/usher" "mchess_server/utils" "net/http" "sync" "github.com/gin-gonic/gin" "github.com/google/uuid" ) var mut sync.Mutex func HostPrivateGameHandler(c *gin.Context) { player := chess.NewPlayer(uuid.New()) u := usher.GetUsher() mut.Lock() defer mut.Unlock() lobby := u.CreateNewPrivateLobby(player) u.AddPlayerToLobbyAndStartGameIfFull(player, lobby) passphrase := lobby.Passphrase.String() info := api.PlayerInfo{ PlayerID: &player.Uuid, LobbyID: &lobby.Uuid, Passphrase: &passphrase, } c.Header("Access-Control-Allow-Origin", "*") c.IndentedJSON(http.StatusOK, info) } func GetLobbyForPassphraseHandler(c *gin.Context) { reqPassphrase := c.Param("phrase") if reqPassphrase == "" { c.IndentedJSON(http.StatusBadRequest, reqPassphrase) return } passPhraseWithSpaces := utils.ConvertToPassphraseWithSpaces(reqPassphrase) lobby := lobbies.GetLobbyRegistry().GetLobbyByPassphrase(passPhraseWithSpaces) if lobby == nil { c.IndentedJSON(http.StatusNotFound, reqPassphrase) return } lobbyInfo := api.LobbyInfo{ ID: &lobby.Uuid, } c.IndentedJSON(http.StatusOK, lobbyInfo) } func RegisterForRandomGame(c *gin.Context) { player := chess.NewPlayer(uuid.New()) usher := usher.GetUsher() mut.Lock() defer mut.Unlock() lobby := usher.WelcomeNewPlayer(player) usher.AddPlayerToLobbyAndStartGameIfFull(player, lobby) info := api.PlayerInfo{ PlayerID: &player.Uuid, LobbyID: &lobby.Uuid, } log.Println("responding with info ", info) c.Header("Access-Control-Allow-Origin", "*") c.IndentedJSON(http.StatusOK, info) } func JoinPrivateGame(c *gin.Context) { req := api.PlayerInfo{} log.Println(c.Request.Body) err := c.ShouldBindJSON(&req) if err != nil || req.Passphrase == nil || *req.Passphrase == "" { c.IndentedJSON(http.StatusNotFound, req) } u := usher.GetUsher() if req.Passphrase != nil && *req.Passphrase != "" && req.PlayerID != nil && req.LobbyID != nil { //is reconnect lobby := u.FindExistingPrivateLobby(utils.Passphrase(*req.Passphrase)) _, found := lobby.GetPlayerByUUID(*req.PlayerID) if found { c.IndentedJSON( http.StatusOK, api.PlayerInfo{ PlayerID: req.PlayerID, LobbyID: req.LobbyID, Passphrase: req.Passphrase, }) return } else { c.IndentedJSON(http.StatusNotFound, req) } } player := chess.NewPlayer(uuid.New()) mut.Lock() defer mut.Unlock() lobby := u.FindExistingPrivateLobby(utils.Passphrase(*req.Passphrase)) if lobby != nil { u.AddPlayerToLobbyAndStartGameIfFull(player, lobby) } else { c.IndentedJSON(http.StatusNotFound, req) return } info := api.PlayerInfo{ PlayerID: &player.Uuid, LobbyID: &lobby.Uuid, Passphrase: req.Passphrase, } c.Header("Access-Control-Allow-Origin", "*") c.IndentedJSON(http.StatusOK, info) }