1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use super::matchmaker::{start_game, GameLobbies, MATCHMAKER_STATE};
use crate::helpers::{generate_unique_id, hash_password};
use anyhow::Result;
use bones_matchmaker_proto::{
    GameID, LobbyId, LobbyInfo, LobbyListItem, MatchInfo, MatchmakerResponse,
};
use iroh::{endpoint::Connection, Endpoint};
use std::collections::HashMap;

/// Handles a request to list lobbies for a specific game
pub async fn handle_list_lobbies(
    game_id: GameID,
    send: &mut iroh::endpoint::SendStream,
) -> Result<()> {
    let state = MATCHMAKER_STATE.lock().await;
    // Retrieve and format lobby information for the specified game
    let lobbies = state
        .game_lobbies
        .get(&game_id)
        .map(|game_lobbies| {
            game_lobbies
                .lobbies
                .iter()
                .map(|(id, lobby_info)| {
                    let current_players = state
                        .lobby_connections
                        .get(&(game_id.clone(), id.clone()))
                        .map(|entry| entry.get().len() as u32)
                        .unwrap_or(0);
                    LobbyListItem {
                        id: id.clone(),
                        name: lobby_info.name.clone(),
                        current_players,
                        max_players: lobby_info.max_players,
                        has_password: lobby_info.password_hash.is_some(),
                        game_id: game_id.clone(),
                    }
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    // Send the lobby list back to the client
    let message = postcard::to_allocvec(&MatchmakerResponse::LobbiesList(lobbies))?;
    send.write_all(&message).await?;
    send.finish()?;
    send.stopped().await?;

    Ok(())
}

/// Handles a request to create a new lobby
pub async fn handle_create_lobby(
    conn: Connection,
    lobby_info: LobbyInfo,
    send: &mut iroh::endpoint::SendStream,
) -> Result<()> {
    let lobby_id = LobbyId(generate_unique_id());
    let mut state = MATCHMAKER_STATE.lock().await;

    // Create or update the game lobbies and insert the new lobby
    state
        .game_lobbies
        .entry(lobby_info.game_id.clone())
        .or_insert_with(|| GameLobbies {
            game_id: lobby_info.game_id.clone(),
            lobbies: HashMap::new(),
        })
        .lobbies
        .insert(lobby_id.clone(), lobby_info.clone());

    // Add the connection to the lobby
    if let Err(e) = state
        .lobby_connections
        .insert((lobby_info.game_id.clone(), lobby_id.clone()), vec![conn])
    {
        error!("Failed to inserting lobby during creation: {:?}", e);
    }

    // Send confirmation to the client
    let message = postcard::to_allocvec(&MatchmakerResponse::LobbyCreated(lobby_id))?;
    send.write_all(&message).await?;
    send.finish()?;
    send.stopped().await?;

    Ok(())
}

/// Handles a request to join an existing lobby
pub async fn handle_join_lobby(
    ep: &Endpoint,
    conn: Connection,
    game_id: GameID,
    lobby_id: LobbyId,
    password: Option<String>,
    send: &mut iroh::endpoint::SendStream,
) -> Result<()> {
    let mut state = MATCHMAKER_STATE.lock().await;

    if let Some(game_lobbies) = state.game_lobbies.get_mut(&game_id) {
        if let Some(lobby_info) = game_lobbies.lobbies.get(&lobby_id) {
            // Check password if the lobby is password-protected
            if let Some(hash) = &lobby_info.password_hash {
                if password.as_ref().map(|p| hash_password(p)) != Some(hash.clone()) {
                    let message = postcard::to_allocvec(&MatchmakerResponse::Error(
                        "Incorrect password".to_string(),
                    ))?;
                    send.write_all(&message).await?;
                    send.finish()?;
                    send.stopped().await?;
                    return Ok(());
                }
            }

            let max_players = lobby_info.max_players;
            let match_data = lobby_info.match_data.clone();
            let player_idx_assignment = lobby_info.player_idx_assignment.clone();

            // Try to add the player to the lobby
            let join_result = state.lobby_connections.update(
                &(game_id.clone(), lobby_id.clone()),
                |_exists, connections| {
                    if connections.len() < max_players as usize {
                        connections.push(conn.clone());
                        Some(connections.len())
                    } else {
                        None
                    }
                },
            );

            match join_result {
                Some(Some(count)) => {
                    // Successfully joined the lobby
                    let message =
                        postcard::to_allocvec(&MatchmakerResponse::LobbyJoined(lobby_id.clone()))?;
                    send.write_all(&message).await?;
                    send.finish()?;
                    send.stopped().await?;

                    // Always notify all players in the lobby about the update
                    let lobby_update_message =
                        postcard::to_allocvec(&MatchmakerResponse::LobbyUpdate {
                            player_count: count as u32,
                        })?;
                    if let Some(connections) = state
                        .lobby_connections
                        .get(&(game_id.clone(), lobby_id.clone()))
                    {
                        for connection in connections.get().iter() {
                            let mut send = connection.open_uni().await?;
                            send.write_all(&lobby_update_message).await?;
                            send.finish()?;
                            send.stopped().await?;
                        }
                    }

                    // Check if the lobby is full and start the match if it is
                    if count == max_players as usize {
                        let match_info = MatchInfo {
                            max_players,
                            match_data,
                            game_id: game_id.clone(),
                            player_idx_assignment,
                        };
                        if let Some(connections) = state
                            .lobby_connections
                            .remove(&(game_id.clone(), lobby_id.clone()))
                        {
                            let members = connections.1;
                            drop(state);
                            let ep = ep.clone();
                            tokio::spawn(async move {
                                if let Err(e) = start_game(ep, members, &match_info).await {
                                    error!("Error starting match from full lobby: {:?}", e);
                                }
                            });
                        }
                    }
                }
                _ => {
                    // Lobby is full
                    let message = postcard::to_allocvec(&MatchmakerResponse::Error(
                        "Lobby is full".to_string(),
                    ))?;
                    send.write_all(&message).await?;
                    send.finish()?;
                    send.stopped().await?;
                }
            }
        } else {
            let message =
                postcard::to_allocvec(&MatchmakerResponse::Error("Lobby not found".to_string()))?;
            send.write_all(&message).await?;
            send.finish()?;
            send.stopped().await?;
        }
    } else {
        let message =
            postcard::to_allocvec(&MatchmakerResponse::Error("Game not found".to_string()))?;
        send.write_all(&message).await?;
        send.finish()?;
        send.stopped().await?;
    }

    Ok(())
}